package com.sam.im.heiqun.uis.activities;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.google.gson.Gson;
import com.iceteck.silicompressorr.SiliCompressor;
import com.melink.bqmmsdk.bean.Emoji;
import com.melink.bqmmsdk.sdk.BQMM;
import com.melink.bqmmsdk.sdk.BQMMMessageHelper;
import com.melink.bqmmsdk.sdk.IBqmmSendMessageListener;
import com.melink.bqmmsdk.widget.BQMMMessageText;
import com.orm.util.Collection;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.dialog.NotificationMsgDialog;
import com.sam.im.heiqun.entities.AAentivity;
import com.sam.im.heiqun.entities.AiteEntivity;
import com.sam.im.heiqun.entities.FanYiBean;
import com.sam.im.heiqun.entities.FileMsgEntivity;
import com.sam.im.heiqun.entities.GroupFriendEntivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.ImageEntity;
import com.sam.im.heiqun.entities.ImageSendEntity;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.entities.PathEntivity;
import com.sam.im.heiqun.entities.PayString;
import com.sam.im.heiqun.entities.RedPacketEntivity;
import com.sam.im.heiqun.entities.RedPacketHistoryEntivity;
import com.sam.im.heiqun.entities.SearchUserEntity;
import com.sam.im.heiqun.entities.TransferEntivity;
import com.sam.im.heiqun.entities.TransfreCreateEntivity;
import com.sam.im.heiqun.entities.UpdateGroupEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.VedioEntity;
import com.sam.im.heiqun.entities.beans.CollectInfo;
import com.sam.im.heiqun.entities.beans.ImageInfoBean;
import com.sam.im.heiqun.entities.event.EventAnExcuseGroup;
import com.sam.im.heiqun.entities.model.FileProEtivity;
import com.sam.im.heiqun.entities.model.LocationEntivity;
import com.sam.im.heiqun.entities.model.WithdrawEntity;
import com.sam.im.heiqun.nets.PGApi;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.ChatGroupRecyclerAdapter;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.beans.BGchat;
import com.sam.im.heiqun.uis.beans.BGsetAll;
import com.sam.im.heiqun.uis.dialogs.MyAlertDialogManages;
import com.sam.im.heiqun.uis.widgets.ChatBottomViews;
import com.sam.im.heiqun.uis.widgets.pulltorefresh.WrapContentLinearLayoutManager;
import com.sam.im.heiqun.uis.widgets.pulltorefresh.base.PullToRefreshView;
import com.sam.im.heiqun.utils.ContentUtils;
import com.sam.im.heiqun.utils.DateFormatUtil;
import com.sam.im.heiqun.utils.DialogUtils;
import com.sam.im.heiqun.utils.EventBusTypeData;
import com.sam.im.heiqun.utils.EventBusTypeObject;
import com.sam.im.heiqun.utils.HttpAssist;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.IMMessageUtil;
import com.sam.im.heiqun.utils.JsonUtil;
import com.sam.im.heiqun.utils.KeyBoardUtils;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.RxJavaUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.view.PullToRefreshListener;
import com.sam.im.heiqun.view.PullToRefreshRecyclerView;
import com.sam.im.heiqun.view.RecordButton;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.utils.ActivityUtil;
import com.yuyh.library.utils.EventBusType;
import com.yuyh.library.utils.StringUtils;
import com.yuyh.library.utils.Utils;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.socket.client.Ack;
import io.socket.client.Socket;

/**
 * 群聊
 * //这里UUID与iOS联通，UUID作为唯一标识，所以本地拼接，规则：聊天类型（单聊是1，群聊是2）+“-”+目标id+“-”+我的id+“-”+时间戳；
 */
public class ChatGroupActivity extends ChatGroupBaseActivity implements
        ChatGroupRecyclerAdapter.IItemHeadImageClickBack, TextWatcher, View.OnLayoutChangeListener {

    private static final int SEND_CLEAN = 1000;
    public static final int REQUST_SENDTOFRIEND = 111;//发送消息给好友
    public static final int AITE_FRIENDS = 1212;//@好友
    public static final int RESULT_SEND_FILE = 112;//发送文件
    public static final int COMMIT_FINISH = 202;//文件上传完毕
    public static final int FILE_DOWNLOAD_OK = 222; //文件下载完毕
    public static final int VEDIO_FINISH = 212;//视屏上传完毕
    private static final int RESULT_TRANSFER_GET = 103;
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.right)
    ImageView right;

    /*@BindView(R.id.red_packet)
    LinearLayout redPacket;
    @BindView(R.id.transfer_accounts)
    LinearLayout transfer_accounts;*/

    @BindView(R.id.red_0)
    ImageView red0;
    @BindView(R.id.red_1)
    ImageView red1;
    @BindView(R.id.red_2)
    ImageView red2;
    @BindView(R.id.red_3)
    ImageView red3;
    @BindView(R.id.red_4)
    ImageView red4;
    @BindView(R.id.red_5)
    ImageView red5;
    @BindView(R.id.red_6)
    ImageView red6;
    @BindView(R.id.red_7)
    ImageView red7;
    @BindView(R.id.red_8)
    ImageView red8;
    @BindView(R.id.red_9)
    ImageView red9;
    @BindView(R.id.red_10)
    ImageView red10;
    @BindView(R.id.red_11)
    ImageView red11;
    @BindView(R.id.red_12)
    ImageView red12;
    @BindView(R.id.red_13)
    ImageView red13;
    @BindView(R.id.tv_aite)
    Button tvAite;
    @BindView(R.id.imgdelete)
    ImageView imgDelete;
    @BindView(R.id.loading)
    ProgressBar loading;

    @BindView(R.id.linear_bottom_kl)
    LinearLayout linear_bottom_kl;
    @BindView(R.id.txt_kl_content)
    TextView txt_kl_content;

    @BindView(R.id.txt_nospick)
    TextView txt_nospick;
    @BindView(R.id.voice_tv)
    TextView voice_tv;

    @BindView(R.id.voice_btn)
    TextView voice_btn;
    @BindView(R.id.mess_et)
    TextView mess_et;
    @BindView(R.id.relative_level_all)
    RelativeLayout relative_level_all;
    @BindView(R.id.level_ok)
    Button level_ok;
    @BindView(R.id.vip_ok_expired)
    Button vip_ok_expired;
    @BindView(R.id.level_clean1)
    Button level_clean1;
    @BindView(R.id.relative_vip_out_of_date)
    RelativeLayout relativeVipOutOfDate;
    @BindView(R.id.relative_vip_out_of_date1)
    RelativeLayout relativeVipOutOfDate1;
    @BindView(R.id.group_membership_has_expired_id)
    RelativeLayout group_membership_has_expired;
    @BindView(R.id.group_membership_has_expired_tx_id)
    TextView group_membership_has_expired_tx;

    @BindView(R.id.tv_vip_out_of_date_tips1)
    TextView tvVipOutOfDateTips1;
    @BindView(R.id.tv_vip_out_of_date_tips)
    TextView tvVipOutOfDateTips;
    @BindView(R.id.iv_chat_background)
    ImageView ivChatBackground;
    @BindView(R.id.remind_group_members_to_expire_id)
    TextView remind_group_members_to_expire;
    private AnimatorSet set;
    private int height;
    private String redPackageId;

    private PullToRefreshRecyclerView myList;
    private ChatGroupRecyclerAdapter tbAdapter;
    private SendMessageHandler sendMessageHandler;
    private static WrapContentLinearLayoutManager wcLinearLayoutManger;

    private Socket mSocket;
    private ImFriendEntivity imFriendEntivity;
    private List<ImFriendEntivity> mFriendEntivities = new ArrayList<>();

    private String uuid = "";
    private Gson gson;
    private static final int RESULT_RED_PACKET_SEND = 101;
    private String TAG = "ChatGroupActivity";
    private PGService mPgService;
    private Dialog redDialog;

    private UserEntivity userEntivity;
    private int screenHeight;
    private static View v;
    private AudioManager audioManager = null;
    private boolean isspeakerphone;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x100:
                    shuxingSet(red7, 4600, 120, 700);
                    shuxingSet(red8, 3100, 110, 300);
                    shuxingSet(red9, 4200, 80, 500);
                    shuxingSet(red10, 2800, 50, 380);
                    shuxingSet(red11, 4700, -70, 400);
                    shuxingSet(red12, 3400, -120, 700);
                    shuxingSet(red13, 6100, -70, 3300);
                    handler.sendEmptyMessageDelayed(0x110, 3300);
                    break;
                case 0x110:
                    doRainRed();
                    break;
            }
        }
    };
    private static int visibPosition;
    private static int firstTag = -1;
    private PopupMenu popupMenu;
    private Menu menu;
    private long sendMsgId;
    private String sendmsgId;
    private ImMessage choseimMessage;
    private BQMM bqmm;
    private ImMessage getmessage;
    private boolean isfirsttag = true;
    private String friendname;
    // private String friendid;
    private List<Long> friendids = new ArrayList<>();
    private FileMsgEntivity fileMsgEntivity;
    //private ImMessage fileimMessage;
    //private ImMessage vedioMessage;
    private String redPacketInfo;
    private String transFromId = "";
    private int groupmembersizes = 0;
    private long id;
    private static final int UP_ERROR = 3209;

    private ImMessage mredPacketImMessage;
    private List<ImMessage> mRedMessages = new ArrayList<>();
    private NotificationMsgDialog msgDialog;

    @Override
    public int getContentViewId() {
        return R.layout.activity_chat_group;
    }

    @Override
    protected String getTitleText() {
        right.setVisibility(View.VISIBLE);
        right.setImageResource(R.drawable.double_people);
        mGroupEntivity = (ImGroupEntivity) getIntent().getSerializableExtra("groupSeri");
        id = getIntent().getLongExtra("groupid", 0l);
        if (mGroupEntivity == null) {
            mGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, id);
        }
        mGroupEntivity.setId(id);
        destid = mGroupEntivity.getId();
        return mGroupEntivity.getName();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onUpdateGroupName(UpdateGroupEntivity event) {
        if (event.getCode() == 2001) {
            if (null != mGroupEntivity) mGroupEntivity.setName(event.getName());
            Log.i("info", "设置title===1");
            List<GroupFriendEntivity> groupUserSss = ToolsUtils.getGroupUserSss(id);
            /**
             * 这里暂时将人数删除
             */
            preTvTitle.setText(event.getName() + "(" + groupUserSss.size() + ")");
//            preTvTitle.setText(event.getName());

            List<ImGroupEntivity> imGroupEntivities = ImGroupEntivity.find(ImGroupEntivity.class, "creater_id = ?", new String[]{event.getId()});

            if (imGroupEntivities.size() > 0) {
                preTvTitle.setText(event.getName() + "(" + mFriendEntivities.size() + ")");
            }

        }
    }

    //艾特消息已读
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onAiteisRead(String event) {
        if (event.equals(getString(R.string.aiteisread))) {
            // tvAite.setVisibility(View.GONE);
        }
    }

    //全体禁言
    @Subscribe
    public void onAnExcuse(EventAnExcuseGroup eventAnExcuseGroup) {
        updateMySpeakState();
    }

    //艾特消息已读
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onUpdateList(Integer event) {
        if (event == EventBusType.REFRESH_GROUP_CHAT_LIST) {
            // tvAite.setVisibility(View.GONE);
            try {
                mGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, id);
                tbAdapter.setGroupEntivity(mGroupEntivity);
                tbAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (event == EventBusType.GROUP_NOSPICK_GRPOUP_REFRENSH) {
            updateMySpeakState();
        } else if (event == EventBusType.GROUP_APPLY_GRPOUP_LEVEL_N) {
            try {
                getGroupLevelState();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (event == EventBusType.GROUP_ADD_USER) {
            try {
                getGroupMember(destid, fromid);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //艾特消息已读
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onUpdateList(EventBusTypeData event) {
        if (null != event) {
            switch (event.getType()) {
                case EventBusType.GROUP_APPLY_GRPOUP_OUT:
                    if (event.getMsg().equals("" + destid)) {
                        showToast("您已被踢出群组！");
                        finish();
                    }
                    break;
                case EventBusType.GROUP_APPLY_GRPOUP_OUT_OTH:
                    List<GroupFriendEntivity> groupFriendEntivities2 = ToolsUtils.groupUserRemoval(GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=?", new String[]{"" + destid}));
                    if (null != groupFriendEntivities2) {
                        if (null != mGroupEntivity)
                            preTvTitle.setText(mGroupEntivity.getName() + "(" + groupFriendEntivities2.size() + ")");
                    }
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addGroupUser(GroupFriendEntivity entivity) {
        mFriendEntivities.add(entivity.getImFriend());
        tbAdapter.setImFriendEntivity(mFriendEntivities);
        tbAdapter.notifyDataSetChanged();
        if (null != mGroupEntivity) {
            List<ImFriendEntivity> allGroupUeaer = ToolsUtils.getAllGroupUeaer(id + "");
            /**+
             * 这里暂时将人数删除
             */
            preTvTitle.setText(mGroupEntivity.getName() + "(" + allGroupUeaer.size() + ")");
//            preTvTitle.setText(mGroupEntivity.getName());
        }
    }

    private void initGroupLevel() {
        try {
            ImGroupEntivity mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, destid);
            if (null != mImGroupEntivity && ("" + mImGroupEntivity.getCreaterId()).equals(ToolsUtils.getMyUserId())) {//我是群主
                level_ok.setText("去续费");
            } else {
                remind_group_members_to_expire.setText("该群已到期，请提示群主续费!");
                level_ok.setText("知道了");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 对群好友列表进行去重操作
     */
    private void initRemovalRemove() {
        try {
            List<GroupFriendEntivity> groupFriendEntivities2 = ToolsUtils.groupUserRemoval(GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? ", new String[]{"" + destid}));
            if (null != groupFriendEntivities2 && groupFriendEntivities2.size() > 0) {
                int a = 0;
                for (GroupFriendEntivity groupfriend : groupFriendEntivities2
                        ) {
                    for (GroupFriendEntivity groupfriend2 : groupFriendEntivities2
                            ) {
                        if (("" + groupfriend.getId()).equals(groupfriend2.getId())) {
                            groupfriend.delete();
                            groupFriendEntivities2.remove(a);
                        }
                    }
                    a++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 防止点击穿透问题.设置图层的触摸监听，即消耗掉点击 .因为之前那个人写的好奇葩，不是弹出，所以只能禁止掉他的点击去
     */

    private void NoPenetratingClicks(){

        relative_level_all.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });

        group_membership_has_expired.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });

        relativeVipOutOfDate.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });

        relativeVipOutOfDate1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });
    }

    @Override
    protected void init() {
        if (mGroupEntivity != null) {
            tvTitle.setText(mGroupEntivity.getName());
        }
        //initData();

        //防止点击穿透问题.设置图层的触摸监听，即消耗掉点击 .因为之前那个人写的好奇葩，不是弹出，所以只能禁止掉他的点击去
        NoPenetratingClicks();
        initGroupLevel();
        initRemovalRemove();
        setChatBG();
        mEditTextContent.addTextChangedListener(this);
        height = getWindowManager().getDefaultDisplay().getHeight();
        mPgService = PGService.getInstance();
        // transfer_accounts.setVisibility(View.INVISIBLE);//群聊需要隐藏转账
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//点了屏幕
        EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
        gson = new Gson();
        uuid = Utils.getUDID(ChatGroupActivity.this);
        userEntivity = ToolsUtils.getUser();
        fromid = "" + userEntivity.getId();
//        if (sendMessageHandler != null) {
//            sendMessageHandler.sendEmptyMessage(PULL_TO_REFRESH_DOWN);
//        }
        initGroupLevel();//群到期群主跟群成员做出提示
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel((int) destid);//注销单人聊天
        mSocket = App.getInstance().getSocket();
        Collections.reverse(tblist);

        tbAdapter = new ChatGroupRecyclerAdapter(this, tblist, new ChatGroupRecyclerAdapter.onLongClickMsgListenler() {
            @Override
            public void longClick(View view, int position, int type) {
                choseimMessage = tblist.get(position);
                sendmsgId = choseimMessage.getMsgId();
                //根据消息id撤回
                sendMsgId = choseimMessage.getId();
                Long sendTime = choseimMessage.getSendTime();
                long nowtime = System.currentTimeMillis();
                long l = (nowtime - sendTime) / (1000 * 60);//时间差两分钟内
                Log.i(TAG, "longClick: ============");
                switch (type) {
                    case ChatRecyclerAdapter.FROM_USER_IMG:
                        ImageSendEntity sendEntity = JsonUtil.toObject(choseimMessage.getContent(), ImageSendEntity.class);
                        boolean canForward = sendEntity == null || sendEntity.isCanForward();
                        initMenu(view, false, ChatRecyclerAdapter.FROM_USER_IMG,canForward);
                        break;
                    case ChatRecyclerAdapter.TO_USER_IMG:
                        if (l <= 2) {
                            initMenu(view, true, ChatRecyclerAdapter.TO_USER_IMG,true);
                        } else {
                            initMenu(view, false, ChatRecyclerAdapter.TO_USER_IMG,true);
                        }
                        break;
//                    case ChatRecyclerAdapter.FROM_USER_LOCATION:
//                        initMenu(view, false, ChatRecyclerAdapter.FROM_USER_LOCATION);
//                        break;
//                    case ChatRecyclerAdapter.TO_USER_LOCATION:
//                        if (l <= 2) {
//                            initMenu(view, true, ChatRecyclerAdapter.TO_USER_LOCATION);
//                        } else {
//                            initMenu(view, false, ChatRecyclerAdapter.TO_USER_LOCATION);
//                        }
//                        break;
                    case ChatRecyclerAdapter.FROM_USER_MSG:
                        initMenu(view, false, ChatRecyclerAdapter.FROM_USER_MSG,true);
                        break;
                    case ChatRecyclerAdapter.TO_USER_EMOJI:
                        if (l <= 2) {
                            initMenu(view, true, ChatRecyclerAdapter.TO_USER_EMOJI,true);
                        } else {
                            initMenu(view, false, ChatRecyclerAdapter.TO_USER_EMOJI,true);
                        }
                        break;
                    case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
                        if (l <= 2) {
                            initMenu(view, true, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT,true);
                        } else {
                            initMenu(view, false, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT,true);
                        }
                        break;
                    case ChatRecyclerAdapter.FROM_USER_EMOJI:
                        initMenu(view, false, ChatRecyclerAdapter.FROM_USER_EMOJI,true);
                        break;
                    case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
                        initMenu(view, false, ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT,true);
                        break;
                    case ChatRecyclerAdapter.TO_USER_MSG:
                        if (l <= 2) {
                            initMenu(view, true, ChatRecyclerAdapter.TO_USER_MSG,true);
                        } else {
                            initMenu(view, false, ChatRecyclerAdapter.TO_USER_MSG,true);
                        }
                        break;
                    case ChatRecyclerAdapter.FROM_USER_VOICE:
                        initMenu(view, false, ChatRecyclerAdapter.FROM_USER_VOICE,true);
                        break;
                    case ChatRecyclerAdapter.TO_USER_VOICE:
                        if (l <= 2) {
                            initMenu(view, true, ChatRecyclerAdapter.TO_USER_VOICE,true);
                        } else {
                            initMenu(view, false, ChatRecyclerAdapter.TO_USER_VOICE,true);
                        }
                        break;
                    case ChatRecyclerAdapter.FROM_USER_VEDIO:
                        VedioEntity vedioEntity = JSON.parseObject(choseimMessage.getContent(), VedioEntity.class);
                        initMenu(view, false, ChatRecyclerAdapter.FROM_USER_VEDIO,vedioEntity.isCanForward());
                        break;
                    case ChatRecyclerAdapter.TO_USER_VEDIO:
                        if (l <= 2) {
                            initMenu(view, true, ChatRecyclerAdapter.TO_USER_VEDIO,true);
                        } else {
                            initMenu(view, false, ChatRecyclerAdapter.TO_USER_VEDIO,true);
                        }
                        break;
                    case ChatRecyclerAdapter.TO_USER_FILE:
                        if (l <= 2) {
                            initMenu(view, true, ChatRecyclerAdapter.TO_USER_FILE,true);
                        } else {
                            initMenu(view, false, ChatRecyclerAdapter.TO_USER_FILE,true);
                        }
                        break;
                    case ChatRecyclerAdapter.FROM_USER_FILE:
                        initMenu(view, false, ChatRecyclerAdapter.FROM_USER_FILE,true);
                        break;
                    case ChatRecyclerAdapter.FROM_USER_READDELETE:
                    case ChatRecyclerAdapter.TO_USER_READDELETE:
                        String imageUrlSrc = "";
                        // Log.i("info","适配器接收到的内容=="+tbub.toString());
                        if (tblist.get(position).getFilePath() != null && !tblist.get(position).getFilePath().equals("")) {
                            imageUrlSrc = tblist.get(position).getFilePath();
                        } else if (tblist.get(position).getFileUrl() != null) {
                            imageUrlSrc = tblist.get(position).getFileUrl();
                        }
                        imgDelete.setVisibility(View.VISIBLE);

                        Glide.with(ChatGroupActivity.this).load(imageUrlSrc).into(new GlideDrawableImageViewTarget(imgDelete) {
                            @Override
                            public void onLoadStarted(Drawable placeholder) {
                                super.onLoadStarted(placeholder);
                               /* if(smallImageView!=null){
                                    smallImageView.setVisibility(View.VISIBLE);
                                    Glide.with(context).load(imgurl).into(smallImageView);
                                }*/
                                loading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(View.GONE);
                                }*/
                                loading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                                super.onResourceReady(resource, animation);
                                loading.setVisibility(View.GONE);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(View.GONE);
                                }*/
                            }
                        });
                        break;


                }

            }
        });
        //阅后即焚删除
        tbAdapter.setOnTouchUplistener(new ChatGroupRecyclerAdapter.OnTouchUplistener() {
            @Override
            public void onTouchup(int position) {
                ImMessage touchmessage = tblist.get(position);
                imgDelete.setVisibility(View.GONE);
                tblist.remove(position);
                tbAdapter.notifyDataSetChanged();
                List<ImMessage> imMessages = ImMessage.find(ImMessage.class, "msg_id=?", new String[]{touchmessage.getMsgId()});
                if (imMessages.size() > 0) {
                    imMessages.get(0).delete();
                }
            }
        });
        tbAdapter.setFriendnicknames(preTvTitle.getText().toString());//这里获取好有名字待优化，每次去查询不科学
        tbAdapter.setImageClickBack(this);
        wcLinearLayoutManger = new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        // wcLinearLayoutManger.setStackFromEnd(true);
        myList.setAdapter(tbAdapter);
        myList.setLayoutManager(wcLinearLayoutManger);
        ((SimpleItemAnimator) myList.getItemAnimator()).setSupportsChangeAnimations(false);

        sendMessageHandler = new SendMessageHandler(this);
        tbAdapter.isPicRefresh = true;
        tbAdapter.notifyDataSetChanged();
        tbAdapter.setSendErrorListener(new ChatGroupRecyclerAdapter.SendErrorListener() {

            @Override
            public void onClick(int position) {
                final ImMessage tbub = tblist.get(position);
                tbub.setSendState(Constant.SENDING);
                tbub.save();
                sendMessageHandler.sendEmptyMessage(SEND_OK);
                socketSend(tbub, null, 0, 0);
            }

        });
        tbAdapter.setVoiceIsReadListener(new ChatGroupRecyclerAdapter.VoiceIsRead() {

            @Override
            public void voiceOnClick(int position) {
                // TODO Auto-generated method stub
                for (int i = 0; i < tbAdapter.unReadPosition.size(); i++) {
                    if (tbAdapter.unReadPosition.get(i).equals(position + "")) {
                        tbAdapter.unReadPosition.remove(i);
                        break;
                    }
                }
            }

        });
        tbAdapter.setRedPacketListener(new ChatGroupRecyclerAdapter.RedPacketOnClick() {
            @Override
            public void redOnClick(ImMessage imMessage, int type) {
                String content = imMessage.getContent();
                Bundle bundle = new Bundle();
                switch (type) {//0-获取；1-发送
                    case 0://
                    case 1:
                        redPacketInfo = ToolsUtils.getRedPacketInfo(content);
                        getRedPacketHistory(redPacketInfo, imMessage);
//                        break;
//                        Bundle bundle = new Bundle();
//                        bundle.putString("redPacketId", ToolsUtils.getRedPacketInfo(content));
//                        startActivity(RedPackageDetailsActivity.class, bundle);
                        break;
                    case 2://转账
                        transFromId = "" + imMessage.getFromid();

                        TransferEntivity transferEntivity = ToolsUtils.getTransfer(content);
                        if (null != transferEntivity && null != transferEntivity.getDestId() && !TextUtils.isEmpty(transferEntivity.getDestId())) {
                            if (!transferEntivity.getDestId().equals(ToolsUtils.getMyUserId())) {
                                showToast("您不是收款人！");
                                return;
                            }
                        }

                        bundle.putString("transferId", ToolsUtils.getTransferInfo(content));
                        bundle.putInt("type", 1);
                        startActivityForResult(AffirmReceiveTransferActivity.class, RESULT_TRANSFER_GET, bundle);
                        break;
                    case 3://发送或接收的转账

//                        TransferEntivity transferEntivity2 = ToolsUtils.getTransfer(content);
//                        if (null!=transferEntivity2 && null!=transferEntivity2.getDestId() && !TextUtils.isEmpty(transferEntivity2.getDestId())){
//                            if (!transferEntivity2.getDestId().equals(ToolsUtils.getMyUserId())){
//                                showToast("您不是收款人！");
//                                return;
//                            }
//                        }

                        bundle.putString("transferId", ToolsUtils.getTransferInfo(content));
                        bundle.putInt("type", 0);
                        startActivity(AffirmReceiveTransferActivity.class, bundle);
                        break;
                }
            }
        });
        tbAdapter.setFanYiListener(new ChatGroupRecyclerAdapter.FanYiOnClick() {
            @Override
            public void fanYiOnClick(String content, int type, int isRefresh) {//isRefresh=0-不是；1-是并显示；2-是并隐藏
                if (0 == isRefresh) {
                    getFanYi(content, type);
                } else {
                    ImMessage imm = tblist.get(type);
                    if (1 == isRefresh) {
                        imm.setIsShowFY("1");
                    } else {
                        imm.setIsShowFY("0");
                    }
                    tblist.set(type, imm);
                    sendMessageHandler.sendEmptyMessage(REFRESH_FANYI);

                }

            }
        });
        //@消息已读 对应去删除@列表中的数据
        tbAdapter.setOnReadAiteListenler(new ChatGroupRecyclerAdapter.onReadAiteListenler() {
            @Override
            public void isRead(ImMessage thub) {
                Iterator<AiteEntivity> all1 = AiteEntivity.findAll(AiteEntivity.class);
                if (all1.hasNext()) {
                    while (all1.hasNext()) {
                        AiteEntivity next = all1.next();
                        if (next != null) {
                            if (next.getMsgId().equals(thub.getMsgId())) {
                                next.delete();
                            }
                        }
                        if (next.getDestId().equals(thub.getFromid())) {
                            tvAite.setVisibility(View.VISIBLE);
                            break;
                        }
                        tvAite.setVisibility(View.GONE);
                    }
                } else {
                    tvAite.setVisibility(View.GONE);//没有@消息了
                }


            }
        });
        //文件点击事件
        tbAdapter.setOnclickDownloadListenler(new ChatGroupRecyclerAdapter.OnclickDownloadListenler() {
            @Override
            public void clickDown(final int positon, final int type) {// 0  接收  1  发送
                switch (type) {
                    case ChatGroupRecyclerAdapter.FROM_USER_FILE://接收
                        AlertDialog.Builder builder = new AlertDialog.Builder(ChatGroupActivity.this);
                        builder.setTitle(getResources().getString(R.string.tip_down));
                        builder.setMessage(getResources().getString(R.string.start_down_file));
                        builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                final ImMessage imMessage = ImMessage.findById(ImMessage.class, tblist.get(positon).getId());
                                String content = imMessage.getContent();
                                final FileMsgEntivity fileMsgEntivity = new Gson().fromJson(content, FileMsgEntivity.class);
                                final String fileUrl = fileMsgEntivity.getFileUrl();
                                if (fileUrl != null) {
                                    if (!ToolsUtils.isExsite(fileUrl)) {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                String s1 = HttpAssist.fileDown(fileUrl, 0, imMessage.getMsgId());
                                                fileMsgEntivity.setFilished(true);
                                                fileMsgEntivity.setFileUrl(fileUrl);
                                                String s = new Gson().toJson(fileMsgEntivity);
                                                tblist.get(positon).setFilePath(s1);
                                                tblist.get(positon).setContent(s);
                                                imMessage.setFilePath(s1);
                                                imMessage.setContent(s);
                                                imMessage.save();
                                                sendMessageHandler.sendEmptyMessage(FILE_DOWNLOAD_OK);
                                            }
                                        }).start();
                                    } else {
                                        fileMsgEntivity.setFilished(true);
                                        String s = new Gson().toJson(fileMsgEntivity, FileMsgEntivity.class);
                                        imMessage.setContent(s);
                                        tblist.get(positon).setContent(s);
                                        imMessage.save();
                                        sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                                    }
                                }
                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                        break;
                    case ChatRecyclerAdapter.TO_USER_FILE://发送的文件
                        ImMessage imMessage1 = tblist.get(positon);
                        String filePath1 = imMessage1.getFilePath();
                        Intent intent = ToolsUtils.openFile(filePath1);
                        if (intent != null) {
                            startActivity(intent);
                        } else {
                            showToast(getString(R.string.fileisdelete));
                        }
                        break;
                    case ChatRecyclerAdapter.TO_USER_VEDIO://用户暂时直接从本地读取
                        ImMessage immessage = tblist.get(positon);
                        String filePath = immessage.getFilePath();
                        String filepath = "";
                        VedioEntity vedioEntity = new Gson().fromJson(immessage.getContent(), VedioEntity.class);
                        PathEntivity pathEntivity = new Gson().fromJson(filePath, PathEntivity.class);
                        if (pathEntivity != null && null != pathEntivity.getVideoPath() && pathEntivity.getVideoPath().contains("storage")) {
                            File file = new File(pathEntivity.getVideoPath());
                            if (file.exists()) {//如果文件存在则从本地读取，不存在从网络路径读取
                                filepath = pathEntivity.getVideoPath();
                            } else {
                                filepath = vedioEntity.getVedioUrl();
                            }
                        } else {
                            filepath = vedioEntity.getVedioUrl();
                        }
                        startActivity(Play2Activity.newIntent(ChatGroupActivity.this,filepath,vedioEntity,null));
                        break;
                    case ChatRecyclerAdapter.FROM_USER_VEDIO:
                        ImMessage imMessage = tblist.get(positon);
                        String content = imMessage.getContent();
                        vedioEntity = new Gson().fromJson(content, VedioEntity.class);
                        String vedioUrl = vedioEntity.getVedioUrl();
                        startActivity(Play2Activity.newIntent(ChatGroupActivity.this,vedioUrl,vedioEntity, CollectInfo.fromImMessage(imMessage)));
                        break;
                }
            }
        });
        voiceBtn.setOnFinishedRecordListener(new RecordButton.OnFinishedRecordListener() {
            @Override
            public void onFinishedRecord(String s) {
                MediaPlayer mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(s);
                    mediaPlayer.prepare();
                    int duration = mediaPlayer.getDuration();
                    float times = duration / 1000;
                    sendVoice(times, s);
                    mediaPlayer.release();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void readCancel() {

            }

            @Override
            public void noCancel() {

            }

            @Override
            public void onActionDown() {

            }

            @Override
            public void onActionUp() {

            }

            @Override
            public void onActionMove() {

            }
        });
       /* voiceBtn.setAudioFinishRecorderListener(new AudioRecordButton.AudioFinishRecorderListener() {
            @Override
            public void onFinished(float seconds, String filePath) {
                sendVoice(seconds, filePath);
            }

            @Override
            public void onStart() {
                tbAdapter.stopPlayVoice();
            }
        });*/
        myList.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView view, int scrollState) {
                state = 0;
                switch (scrollState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        tbAdapter.handler.removeCallbacksAndMessages(null);
                        tbAdapter.setIsGif(true);
                        tbAdapter.isPicRefresh = false;
//                        tbAdapter.notifyDataSetChanged();
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        tbAdapter.handler.removeCallbacksAndMessages(null);
                        tbAdapter.setIsGif(false);
                        tbAdapter.isPicRefresh = true;
                        reset();
                        KeyBoardUtils.hideKeyBoard(ChatGroupActivity.this,
                                mEditTextContent);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        myList.setAlpha(0f);
        groupFriendsNumber();
        getmessage = (ImMessage) getIntent().getSerializableExtra("msg");
        super.init();//所有新添加的发送消息写在这后面
        if (null != getmessage) {//转发消息
            sendMessagefromother();
        }
        searchAiteNums();
        tbAdapter.setGroupEntivity(mGroupEntivity);
    }

    private void initData() {
        if (msgDialog == null) {
            msgDialog = new NotificationMsgDialog(this);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    /**
     * 降序
     * -1和0都不交换
     * 1交换
     */
    public static final class ComparatorValues implements Comparator<ImMessage> {
        @Override
        public int compare(ImMessage object1, ImMessage object2) {
            long m1 = 0;
            long m2 = 0;
            try {
                m1 = object1.getSendTime();
                m2 = object2.getSendTime();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (m1 < m2) {
                return 1;
            }
            return -1;

        }
    }

    private Dialog dialog;

    private void getNoReadNotice() {
        try {
            List<ImMessage> imMessageS = new ArrayList<>();
            List<ImMessage> imMessageS1 = ImMessage.find(ImMessage.class, "fromid=? and message_type=?", new String[]{"" + destid, "" + Constant.MESSAGE_TYPR_CALL_ANSWER});
            List<ImMessage> imMessageS2 = ImMessage.find(ImMessage.class, "fromid=? and message_type=?", new String[]{"" + destid, "" + Constant.MESSAGE_TYPR_CALL_OFFER});
            List<ImMessage> imMessageS3 = ImMessage.find(ImMessage.class, "fromid=? and message_type!=?", new String[]{"" + destid, "" + Constant.MESSAGE_TYPR_CALL_OFFER});

            if (null != imMessageS1 && imMessageS1.size() > 0) imMessageS.addAll(imMessageS1);
            if (null != imMessageS2 && imMessageS2.size() > 0) imMessageS.addAll(imMessageS2);
            Collections.sort(imMessageS, new ComparatorValues());
            if (imMessageS.size() > 0) {
                boolean isShow = false;
                for (int j = 0; j < imMessageS.size(); j++) {
                    ImMessage imMessage = imMessageS.get(j);
                    if (!imMessage.isPayed()) {
                        if (!isShow) {
                            if (null == dialog || !dialog.isShowing()) {
                                dialog = MyAlertDialogManages.initShowNoticed(ChatGroupActivity.this, imMessage, null);
                                isShow = true;
                            }
                        } else {
                            imMessage.setPayed(true);
                            imMessage.save();
                        }
                    } else {
                        imMessage.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//
    }

    /*
    检查@消息数
     */
    private void searchAiteNums() {
        Iterator<AiteEntivity> all = AiteEntivity.findAll(AiteEntivity.class);
        if (all.hasNext()) {//这里表示列表中没有数据了
            tvAite.setVisibility(View.VISIBLE);
        } else {
            tvAite.setVisibility(View.GONE);
        }
    }

    //转发消息
    private void sendMessagefromother() {
        setSocket();
        int type = -1;
        getmessage.setDestid(destid);
        String content = getmessage.getContent();
        String imgurl = "";
        switch (getmessage.getMessageType()) {
            case Constant.MESSAGE_TYPR_IMAGE://图片
                type = ChatRecyclerAdapter.TO_USER_IMG;
                if (getmessage.getFileUrl() != null) {
                    imgurl = getmessage.getFileUrl();
                } else {
                    imgurl = getmessage.getContent();
                }

                break;
            case Constant.MESSAGE_TYPR_FILE:
                type = ChatRecyclerAdapter.TO_USER_FILE;
                break;
            case Constant.MESSAGE_TYPR_VEDIO:
                type = ChatRecyclerAdapter.TO_USER_VEDIO;
                break;
            case Constant.MESSAGE_TYPR_VOICE:
                type = ChatRecyclerAdapter.TO_USER_VOICE;
                break;
            case Constant.MESSAGE_TYPR_LOCATION://位置
                type = ChatRecyclerAdapter.TO_USER_LOCATION;
                LocationEntivity locationEntivity = new Gson().fromJson(getmessage.getContent(), LocationEntivity.class);
                imgurl = locationEntivity.getUrl();
                break;
            case Constant.MESSAGE_TYPR_TEXT://文本
                type = ChatRecyclerAdapter.TO_USER_MSG;
                break;
            case Constant.MESSAGE_TYPR_BQEMOJI://表情
                MsgEntity receirvemsg = new Gson().fromJson(content, MsgEntity.class);
                if (receirvemsg.getMsgCodes() != null && !"".equals(receirvemsg.getMsgCodes())) {
                    //大表情
                    type = ChatRecyclerAdapter.TO_USER_EMOJI;
                } else {
                    //图文混排
                    type = ChatRecyclerAdapter.TO_USER_EMOJI_TEXT;
                }
                break;
        }
      /*  imMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_IMG,
                "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_GROUP,
                destid, imgFile.getPath(), Constant.MESSAGE_TYPR_IMAGE,
                currentTime, System.currentTimeMillis(), 0, imgFile.getPath(), fromid + "__" + destid, 0, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());*/
        final ImMessage sendmessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, type, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_GROUP,
                destid, getmessage.getContent(), getmessage.getMessageType(),
                System.currentTimeMillis(), System.currentTimeMillis(), 0, getmessage.getFilePath(), fromid + "__" + destid, getmessage.getUserVoiceTime(), userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());
        tblist.add(sendmessage);
        if (type == ChatRecyclerAdapter.TO_USER_IMG) {
            ImageSendEntity sendEntity = JsonUtil.toObject(getmessage.getContent(), ImageSendEntity.class);
            if(sendEntity != null){
                imageList.add(new ImageInfoBean(sendEntity.getImagePath(), IMMessageUtil.canImageForward(getmessage)));
                imagePosition.put(tblist.size() - 1, imageList.size() - 1);
            }
        }
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(sendmessage, null, 0, 0);
    }

    public void groupFriendsNumber() {
        long count = GroupFriendEntivity.count(GroupFriendEntivity.class, "belong_group_id=?", new String[]{"" + destid});
        getGroupMember(destid, fromid);
        if (count == 0) {//没有群成员的时候需要获取群成员
        } else {
            if (null != mGroupEntivity) {
                /**
                 * 这里暂时将人数删除
                 */
                preTvTitle.setText(mGroupEntivity.getName() + "(" + count + ")");
//                preTvTitle.setText(mGroupEntivity.getName() );
            }
        }
    }

    private void updateMySpeakState() {

        if (isAnExcuse()) {
            //在禁言状态
            //txt_nospick.setVisibility(View.VISIBLE);
            mess_et.setVisibility(View.GONE);
            voice_tv.setVisibility(View.VISIBLE);
            voice_btn.setVisibility(View.GONE);
            voiceIv.setEnabled(false);
            emoji.setEnabled(false);
            mess_iv.setEnabled(false);
            state = 0;
            bqmmKeyboard.setVisibility(View.GONE);
            emoji.setImageResource(R.drawable.emoji);
            KeyBoardUtils.showKeyBoard(ChatGroupActivity.this, mEditTextContent);
        } else {
            txt_nospick.setVisibility(View.GONE);
            mess_et.setVisibility(View.VISIBLE);
            voice_tv.setVisibility(View.GONE);

            voiceIv.setEnabled(true);
            emoji.setEnabled(true);
            mess_iv.setEnabled(true);

            bqmmKeyboard.setVisibility(View.VISIBLE);

        }
    }
    /**
     * 提示群主他的群快到期了
     */
    private void updateFeeOutOfDateState1() {

        try {
            List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and uid=?", String.valueOf(destid), fromid);
            if (null == groupFriendEntivities || groupFriendEntivities.size() <= 0) {
                return;
            }
            GroupFriendEntivity groupFriendEntivity = groupFriendEntivities.get(0);

            ImGroupEntivity mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, destid);

            if (null != mImGroupEntivity) {
                if (null != mImGroupEntivity.getLevel() && !TextUtils.isEmpty(mImGroupEntivity.getLevel())) {
                    int a = Integer.parseInt(mImGroupEntivity.getLevel());
                    if (a > 0) {
                        long time = Long.parseLong(groupFriendEntivity.getExpire()) - System.currentTimeMillis();

                        String role = groupFriendEntivity.getRole();
                        if (time > 0 && time < 72 * 60 * 60 * 1000&&role.equals("1")) {
                            relativeVipOutOfDate1.setVisibility(View.VISIBLE);
                            tvVipOutOfDateTips1.setText(String.format(getResources().getString(R.string.vip_out_of_date_tips1),
                                    DateFormatUtil.transferLastTime1(time)));
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 提示群主和群成员群已经到期
     */
    private void getGroupLevelState() {
        try {
            List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and uid=?", String.valueOf(destid), fromid);
            if (null == groupFriendEntivities || groupFriendEntivities.size() <= 0) {
                return;
            }
            GroupFriendEntivity groupFriendEntivity = groupFriendEntivities.get(0);
            ImGroupEntivity mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, destid);
            if (null != mImGroupEntivity) {
                if (null != mImGroupEntivity.getLevel() && !TextUtils.isEmpty(mImGroupEntivity.getLevel())) {
                    int b = Integer.parseInt(groupFriendEntivity.getLevel());
                    int a = Integer.parseInt(mImGroupEntivity.getLevel());
                    if (a > 0||b>0) {
                        long time = Long.parseLong(groupFriendEntivity.getExpire());
                        if (time <= System.currentTimeMillis()&&time!=0) {
                            //过期了
                            Log.i("info", "返回的等级==" + a);
                            Log.i("info1", "返回的时间==" + time);
                            relative_level_all.setVisibility(View.VISIBLE);
                            state = 0;
                            bqmmKeyboard.setVisibility(View.GONE);
                            emoji.setImageResource(R.drawable.emoji);
                            KeyBoardUtils.showKeyBoard(ChatGroupActivity.this, mEditTextContent);
                            return;
                        }
                    }
                }
            }
            relative_level_all.setVisibility(View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 提示群成员会员快到期，该群已经升级了收费群，在该群已经没有续费了，到时候自动退出
     */
    private void updateFeeOutOfDateState() {
    /***
     * 这里判断，是避免对象初始化，获取不到最新的数据
     */
        if(groupFriendEntivities == null && groupFriendEntivity == null){
            /**
             * 只在初始化页面的时候加载一次数据对象，不然重新创建对象，对象携带不了最新的数据
             */
            groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and uid=?", String.valueOf(destid), fromid);
            if (null == groupFriendEntivities || groupFriendEntivities.size() <= 0) {
                return;
            }
            groupFriendEntivity = groupFriendEntivities.get(0);
        }

        String expire = groupFriendEntivity.getGroupExpire();//群成员的时间
        Log.i("info1","onResome加载数据:"+expire+"------"+destid+"-----"+fromid);
        if (TextUtils.isEmpty(expire)) {
            return;
        }
        long restTime = Long.valueOf(expire) - System.currentTimeMillis();
        long time = Long.parseLong(groupFriendEntivity.getExpire());//獲取到群成員所在群有沒有過期
        int TollGroup = Integer.parseInt(groupFriendEntivity.getDays());//获取到收费的天数来判断该群是否是收费群
        int GroupLevel=Integer.parseInt(groupFriendEntivity.getLevel());//获取群等级，判断等级也要大于0
        String role = groupFriendEntivity.getRole();
        if(restTime>0 &&restTime< 24 * 60 * 60 * 1000*3&&(!role.equals("1"))&&time>System.currentTimeMillis()&&TollGroup>0&&GroupLevel>0){//之前所在群，群主设置了收费，提示群成员还有三天到期
            relativeVipOutOfDate.setVisibility(View.VISIBLE);
            tvVipOutOfDateTips.setText(String.format(getResources().getString(R.string.vip_out_of_date_tips),
                    DateFormatUtil.transferLastTime1(restTime), groupFriendEntivity.getFee(), groupFriendEntivity.getDays()));
            Log.i("dsh","时间跟天数");
        }else if(restTime < 0&&time>System.currentTimeMillis()&&TollGroup>0&&GroupLevel>0){
            group_membership_has_expired.setVisibility(View.VISIBLE);//对群成员在这个群到期了做出提示
            group_membership_has_expired_tx.setText(String.format(getResources().getString(R.string.vip_out_of_date_tips111),
                    groupFriendEntivity.getFee(), groupFriendEntivity.getDays()));

    }
    }

    /**
     * 查询群组好友列表
     */
    private void getGroupMember(final long groupId, String fromid) {
        mPgService.getGroupMember(groupId + "", fromid).subscribe(new AbsAPICallback<SearchUserEntity>() {
            @Override
            public void onNext(final SearchUserEntity friendEntivity) {
                Log.i("info", "查询到的群成员==" + friendEntivity.getInfo().toString());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final List<ImFriendEntivity> mFriendEntivities = friendEntivity.getInfo();
                        ToolsUtils.saveGroupUserS(mFriendEntivities, groupId);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (null != mGroupEntivity) {
                                    /**
                                     * 这里暂时将人数删除
                                     */
                                    preTvTitle.setText(mGroupEntivity.getName() + "(" + mFriendEntivities.size() + ")");
//                                    preTvTitle.setText(mGroupEntivity.getName() );
                                    Log.i(TAG, "run: ----------群成员==" + new Gson().toJson(friendEntivity));

                                }
                            }
                        });

                    }
                }).start();

            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    /**
     * 获取红包详情
     *
     * @param uId
     */
    public void getRedPacketHistory(final String uId, final ImMessage imMessage) {
        if (!ToolsUtils.currentNetState(this)) {//当前网络不可用
            showToast(getResources().getString(R.string.net_error));
            return;
        }
        showProgress(getResources().getString(R.string.now_open));
        mPgService.getRedPacketHistory(uId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<RedPacketHistoryEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(ex.getDisplayMessage());
                hideProgress();
            }

            @Override
            public void onNext(RedPacketHistoryEntivity data) {
                hideProgress();
                gotoreddetail(data, uId, imMessage);
            }
        });
    }

    private void gotoreddetail(RedPacketHistoryEntivity data, final String uId, final ImMessage imMessage) {
        final RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
        if (null != data.getRedPacket() && !"3".equals(data.getRedPacket().getStatus())) {
            if (data.getRedPacket().getRedPacketCount().equals("" + data.getRedPacketHistory().size())) {//已领完
                Bundle bundle = new Bundle();
                bundle.putSerializable("redPacketId", data);
                bundle.putInt("type", 1);
                startActivity(RedPackageDetailsActivity.class, bundle);
            } else {
                if (null == data.getRedPacketHistory() || data.getRedPacketHistory().size() == 0) {//未领取
                    if (null != redPacketEntivity && "3".equals(redPacketEntivity.getRedPacketType())) {

                        mredPacketImMessage = imMessage;

                        String command = "";
                        if (null == redPacketEntivity.getCommand() || "".equals(redPacketEntivity.getCommand())) {
                            command = getResources().getString(R.string.gx_facai);
                        } else {
                            command = redPacketEntivity.getCommand();
                        }
                        txt_kl_content.setText(command);
                        linear_bottom_kl.setVisibility(View.VISIBLE);

                    } else {
                        redDialog = MyAlertDialogManages.initShowRedPacket(ChatGroupActivity.this, data.getRedPacket().getHeadUrl(), data.getRedPacket().getName(), data.getRedPacket().getRedPacketContent(), data.getRedPacket().getRedPacketType(), new MyAlertDialogManages.OnAlertOkImage() {
                            @Override
                            public void onOkImageClick(ImageView mImageView) {
                                ToolsUtils.startAnimal(mImageView);
                                openRedPacket(uId);
                            }
                        });
                    }
                } else {
                    for (int i = 0; i < data.getRedPacketHistory().size(); i++) {
                        if (data.getRedPacketHistory().get(i).getUserId().equals("" + ToolsUtils.getMyUserId())) {//已领取
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("redPacketId", data);
                            bundle.putInt("type", 1);
                            startActivity(RedPackageDetailsActivity.class, bundle);
                            return;
                        }
                    }
                    if (null != redPacketEntivity && "3".equals(redPacketEntivity.getRedPacketType())) {

                        mredPacketImMessage = imMessage;

                        String command = "";
                        if (null == redPacketEntivity.getCommand() || "".equals(redPacketEntivity.getCommand())) {
                            command = getResources().getString(R.string.gx_facai);
                        } else {
                            command = redPacketEntivity.getCommand();
                        }
                        txt_kl_content.setText(command);
                        linear_bottom_kl.setVisibility(View.VISIBLE);

                    } else {
                        redDialog = MyAlertDialogManages.initShowRedPacket(ChatGroupActivity.this, data.getRedPacket().getHeadUrl(), data.getRedPacket().getName(), data.getRedPacket().getRedPacketContent(), data.getRedPacket().getRedPacketType(), new MyAlertDialogManages.OnAlertOkImage() {
                            @Override
                            public void onOkImageClick(ImageView mImageView) {
                                ToolsUtils.startAnimal(mImageView);
                                openRedPacket(uId);
                            }
                        });
                    }
                }
            }
        } else {
            showToast(getResources().getString(R.string.red_package_already_overtime));
        }
    }

    /**
     * 打开红包
     *
     * @param uId
     */
    public void openRedPacket(final String uId) {
        if (!ToolsUtils.currentNetState(this)) {//当前网络不可用
            return;
        }
        mPgService.openRedPacket(uId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                int code = ex.getCode();
                if (null != redDialog) redDialog.dismiss();
                if (code == 3) {
                    ToolsUtils.showToast(ChatGroupActivity.this, getResources().getString(R.string.red_is_old));
                    initRedKLOpenFns(uId);
                    toReadPackHistoryActivity(10, true);
                } else if (code == 4) {
                    toReadPackHistoryActivity(10, false);
                } else {
                    ToolsUtils.showToast(ChatGroupActivity.this, getResources().getString(R.string.open_fail));
                }

            }

            @Override
            public void onNext(String data) {
//                new ToastUtils().showSingleToast(data.getInfo());
                if (null != redDialog) redDialog.dismiss();
                redPackageId = uId;
                initRedKLOpenFns(uId);
                doRainRed();
                toReadPackHistoryActivity(2000, true);
            }
        });
    }

    private void clearMessage() {
        //清空当前聊天对象的未读信息
        List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=? and uniqueness =?", new String[]{fromid, destid + "", "__"});
        if (messageEntivities.size() > 0) {
            MessageEntivity messageEntivity = messageEntivities.get(0);
            messageEntivity.setMessageNum(0);
            MessageEntivity.save(messageEntivity);
        }

        EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
    }

    /**
     * @param //needToScrollView 要滚动的布局,就是说在键盘弹出的时候,你需要试图滚动上去的View,在键盘隐藏的时候,他又会滚动到原来的位置的布局
     * @param// root             最外层布局
     *//*
    private void controlKeyboardLayout(final View root, final View needToScrollView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            private Rect r = new Rect();

            @Override
            public void onGlobalLayout() {
                //获取当前界面可视部分
                ChatGroupActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = ChatGroupActivity.this.getWindow().getDecorView().getRootView().getHeight();
                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;
                int recyclerHeight = 0;
                if (wcLinearLayoutManger != null) {
                    recyclerHeight = wcLinearLayoutManger.getRecyclerHeight();
                }
                if (heightDifference == bottomStatusHeight) {

                    if (emoji_group.getVisibility() == View.VISIBLE) {
                        int contentHeight = wcLinearLayoutManger == null ? 0 : wcLinearLayoutManger.getHeight() - ScreenUtil.dip2px(ChatGroupActivity.this, 210);
                        if (recyclerHeight < contentHeight) {
                            needToScrollView.scrollTo(0, 0);
                        } else {
                            if (recyclerHeight - contentHeight < ScreenUtil.dip2px(ChatGroupActivity.this, 100)) {
                                float h = ScreenUtil.dip2px(ChatGroupActivity.this, ScreenUtil.dip2px(ChatGroupActivity.this, 30));
                                needToScrollView.scrollTo(0, (int) h);
                            } else {
                                float h = ScreenUtil.dip2px(ChatGroupActivity.this, 225);
                                needToScrollView.scrollTo(0, (int) h);
                            }
                        }
                    } else if (tbbv.getVisibility() == View.VISIBLE) {

                        int contentHeight = wcLinearLayoutManger == null ? 0 : wcLinearLayoutManger.getHeight() - ScreenUtil.dip2px(ChatGroupActivity.this, 150);
                        if (recyclerHeight < contentHeight) {
                            needToScrollView.scrollTo(0, 0);
                        } else {
                            float h = ScreenUtil.dip2px(ChatGroupActivity.this, 150) + 50;
                            needToScrollView.scrollTo(0, (int) h);
                        }

                    } else {
                        needToScrollView.scrollTo(0, 0);
                    }
                } else {
                    if (heightDifference < recyclerHeight) {
                        int contentHeight = wcLinearLayoutManger == null ? 0 : wcLinearLayoutManger.getHeight();
                        if (recyclerHeight < contentHeight) {
//                            Log.i(TAG, "onGlobalLayout: 001+");
                            listSlideHeight = heightDifference - (contentHeight - recyclerHeight);
                            needToScrollView.scrollTo(0, listSlideHeight);
                        } else {
//                            Log.i(TAG, "onGlobalLayout: 002+");
                            listSlideHeight = heightDifference;
                            needToScrollView.scrollTo(0, listSlideHeight);
                        }
                    } else {
                        listSlideHeight = 0;
                    }
                }
            }
        });
    }*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onClearEvent(String code)//在ui线程执行
    {
        if (code.equals(Constant.BLACK_CLEAR_GROUP_MESSAGE_REFRESH)) {
            try {
                pagelist.clear();
                tblist.clear();
                myList.setPullRefreshEnabled(false);
                tbAdapter.notifyDataSetChanged();
                showToast(getString(R.string.chat_history_clean_success));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (code.equals(Constant.CLOSE_CHAT_GROUP_ACTIVITY)) {
            finish();
        } else if (code.equals(Constant.APP_DESTID_CHAT_GROUP_ACTIVITY)) {
            App.destid = destid;
        } else if (code.equals(Constant.STAR_PLAY_VOICE)) {//播放语音
            speakerBt.setVisibility(View.VISIBLE);
            speakerBt.setEnabled(true);
        } else if (code.equals(Constant.STOP_PLAY_VOICE)) {//语音播放停止
            speakerBt.setVisibility(View.GONE);
            speakerBt.setEnabled(false);

            tbAdapter.stopPlayVoice(false);

        }
    }

    @Override
    protected void loadRecords() {
        loadmoreMessage();
    }

    /**
     * 头像点击事件
     *
     * @param view
     * @param idLong
     */
    @Override
    public void headImageClick(View view, long idLong) {
        Bundle bundle = new Bundle();
        bundle.putLong("id", idLong);
        bundle.putInt("type", 0);
        startActivityForResult(FriendDetailActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundle);
    }



    @Override
    public void headImageLongClick(View view, long idLong) {

        ImFriendEntivity  imFriendEntivityK= null;
        if (0 != idLong){
            imFriendEntivityK = ToolsUtils.getMyFriendForId(idLong);
        }

        if (imFriendEntivityK != null) {
            friendname = imFriendEntivityK.getName();
            friendids.add(idLong);

            String nnn = (null == imFriendEntivityK.getNickName() || "".equals(imFriendEntivityK.getNickName() )) ? "" + idLong: imFriendEntivityK.getNickName() ;
            mEditTextContent.append("@"+nnn + " ");
        } else {

            getUserById2(idLong );
        }



    }


    /**
     * @param destid
     */
    private void getUserById2(final long destid) {

        String fromid = ToolsUtils.getMyUserId();
        mPgService.getUserById(fromid, destid+"").subscribe(new AbsAPICallback<ImFriendEntivity>() {
            @Override
            public void onNext(ImFriendEntivity mFriendEntivityg) {
                hideProgress();
                boolean isUpdate = false;
                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=?", new String[]{ToolsUtils.getMyUserId() + "", destid + ""}, null, "time desc", null);

                ImFriendEntivity  mMessageEntivity   =mFriendEntivityg;

                friendname = mMessageEntivity.getName();
                friendids.add(destid);
                String nnn = (null == mMessageEntivity.getNickName() || "".equals(mMessageEntivity.getNickName())) ? "" + destid: mMessageEntivity.getNickName();
                mEditTextContent.append("@"+nnn + " ");

            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() > 0) {
            mess_iv.setVisibility(View.GONE);
            sendBtn.setVisibility(View.VISIBLE);
        } else {
            mess_iv.setVisibility(View.VISIBLE);
            sendBtn.setVisibility(View.GONE);
        }
        String s1 = mEditTextContent.getText().toString();
        if (null != s1 && s1.length() > 0 && s1.contains("@") && s1.lastIndexOf("@") == s1.length() - 1) {
            Bundle bundle = new Bundle();
            bundle.putString("tags", "@");
            bundle.putString("groupId", "" + id);
//            startActivityForResult(SelecteLocalFriendActivity.class, AITE_FRIENDS, bundle);
            startActivityForResult(SelecteATFriendActivity.class, AITE_FRIENDS, bundle);
            //  Log.i("info","包含@");
        }
    }

    @Override
    public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
        // Log.i("info", "top ==" + i1 + ",bottom==" + i3 + ",oldtop==" + i5 + ",oldbottom==" + i7);
        if (screenHeight / 4 < (screenHeight - i3) || bqmmKeyboard.getVisibility() == View.VISIBLE || tbbv.getVisibility() == View.VISIBLE) {
            Log.i("info", "弹出键盘");
            if (tblist.size() > 0 && firstTag != -1) {
                Log.i("info", "执行了这里");
                myList.smoothScrollToPosition(tblist.size());
            }
        }
    }

static class SendMessageHandler extends Handler {
    WeakReference<ChatGroupActivity> mActivity;

    SendMessageHandler(ChatGroupActivity activity) {
        mActivity = new WeakReference<ChatGroupActivity>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
        final ChatGroupActivity theActivity = mActivity.get();
        theActivity.tbAdapter.setImagePosition(theActivity.imagePosition);
        theActivity.tbAdapter.setImageList(theActivity.imageList);
        if (theActivity != null) {
            switch (msg.what) {
                case REFRESH:
                    if (firstTag == -1)
                        theActivity.myList.setAlpha(1f);
                    theActivity.tbAdapter.isPicRefresh = true;
                    theActivity.tbAdapter.notifyDataSetChanged();
                    int position = theActivity.tbAdapter.getItemCount() < 0 ? 0 : theActivity.tbAdapter.getItemCount();
                    theActivity.myList.smoothScrollToPosition(position);
                    break;
                case REFRESH_FANYI:
                    theActivity.tbAdapter.isPicRefresh = true;
                    theActivity.tbAdapter.notifyDataSetChanged();
                    break;
                case VEDIO_FINISH:
                    //theActivity.socketSend(theActivity.vedioMessage, null, 0, 0);
                    break;
                case UP_ERROR:
                    theActivity.showToast(theActivity.getResources().getString(R.string.nofile_fail));
                    theActivity.tblist.remove(theActivity.tblist.size() - 1);
                    theActivity.tbAdapter.notifyDataSetChanged();
                    break;
                case SEND_OK:
                    if (theActivity.myList.getAlpha() == 0f) {
                        theActivity.myList.setAlpha(1f);
                    }
                    theActivity.mEditTextContent.setText("");
                    theActivity.tbAdapter.isPicRefresh = true;
                    // theActivity.tbAdapter.setImageList(theActivity.imageList);
                    Log.i("info", "handleMessage: ====SEND_OK=====size============" + theActivity.tblist.size());
                    theActivity.tbAdapter.notifyDataSetChanged();
                    theActivity.myList.smoothScrollToPosition(theActivity.tbAdapter.getItemCount());
                    break;
                case RECERIVE_OK:
                    theActivity.tbAdapter.isPicRefresh = true;
                    theActivity.tbAdapter.notifyDataSetChanged();
                    theActivity.myList.smoothScrollToPosition(theActivity.tbAdapter.getItemCount());
                    if (firstTag == -1)
                        theActivity.myList.setAlpha(1f);
                    break;
                case COMMIT_FINISH://文件上传完毕开始发送消息
                    String s = new Gson().toJson(theActivity.fileMsgEntivity);
                    ImMessage obj = (ImMessage) msg.obj;
                    obj.setContent(s);
                    obj.setSendState(Constant.SENDING);
                    theActivity.socketSend(obj, null, 0, 0);
                    break;
                case FILE_DOWNLOAD_OK://文件下载完毕
                    theActivity.tbAdapter.isPicRefresh = true;
                    theActivity.tbAdapter.notifyDataSetChanged();
                    break;
                case PULL_TO_REFRESH_DOWN:
                    theActivity.pullList.refreshComplete();
                    theActivity.tbAdapter.notifyDataSetChanged();
                    theActivity.myList.setRefreshComplete();
                    Log.i("info", "firsttag==" + firstTag);
                    int alphatime = 0;
                    if (theActivity.tblist.size() <= 5) {
                        alphatime = 80;
                    } else if (theActivity.tblist.size() <= 10) {
                        alphatime = 180;
                    } else {
                        alphatime = 400;
                    }
                    if (firstTag == -1)
                        theActivity.myList.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                theActivity.myList.setAlpha(1f);
                            }
                        }, alphatime);
                    if (theActivity.tbAdapter.getItemCount() <= theActivity.number) {
                        theActivity.myList.smoothScrollToPosition(theActivity.tbAdapter.getItemCount());
                    } else if (v != null && firstTag != -1) {
                        int top = v.getTop();
                        wcLinearLayoutManger.scrollToPositionWithOffset(15, top);
                    }
                    theActivity.isDown = false;
                    firstTag++;
                    break;

                case SEND_CLEAN:
                    theActivity.mEditTextContent.setText("");
                    break;
                default:
                    break;
            }
        }
    }

}

    /**
     * socket发送消息
     *
     * @param tbub
     */
    public void socketSend(final ImMessage tbub, final String address, final double lat, final double lut) {
        Log.i("info", "发送的消息==" + tbub.toString());

        GroupFriendEntivity groupMember = ToolsUtils.getGroupMember(String.valueOf(destid), fromid);
        if (groupMember == null) {
            //不是群成员
            tbub.setSendState(Constant.SENDERROR);
            tbub.save();
            sendMessageHandler.sendEmptyMessage(SEND_OK);
            return;
        }

        if (!isAnExcuse())
            new Thread(new Runnable() {
                boolean sendState = false;
                int retryCount = 0;

                @Override
                public void run() {

                    tbub.save();
                    ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
                    IMMessageToJson.ImMessageToMessageEntivity(imMessage, Constant.FROM_TYPE_SELF);
                    socketSend(imMessage);
                }

                private void socketSend(final ImMessage imMessage) {
                    while (!sendState && retryCount < 2) {
                        if (retryCount == 9) {
                            imMessage.setSendState(Constant.SENDERROR);
                            imMessage.save();
                            tbub.setSendState(Constant.SENDERROR);
                            if (null != tblist) {
                                for (int j = 0; j < tblist.size(); j++) {
                                    if (imMessage.getMsgId().equals(tblist.get(j).getMsgId())) {
                                        tblist.set(j, tbub);
                                    }
                                }
                            }
                            sendMessageHandler.sendEmptyMessage(SEND_OK);
                            return;
                        }
                        try {
                            if (imMessage.getType() == ChatGroupRecyclerAdapter.TO_USER_IMG | imMessage.getType() == ChatGroupRecyclerAdapter.TO_USER_READDELETE)//图片
                            {
                                if (imMessage.getFilePath() != null && imMessage.getFilePath().contains("storage") | imMessage.getFilePath().contains("sdcard")) {
                                    String response = HttpAssist.uploadFile(new File(imMessage.getFilePath()), "", false);
                                    ImageEntity imageEntity = gson.fromJson(response, ImageEntity.class);
                                    String url = imageEntity.getData().getInfo().get(0);
                                    if(imMessage.getMessageType() == ChatRecyclerAdapter.TO_USER_IMG){
                                        ImageSendEntity sendEntity = JsonUtil.toObject(imMessage.getContent(), ImageSendEntity.class);
                                        if(sendEntity != null){
                                            sendEntity.setImagePath(url);
                                            imMessage.setContent(JsonUtil.toJson(sendEntity));
                                        }
                                    }else {
                                        imMessage.setContent(url);
                                    }
                                    imMessage.setFileUrl(url);
                                    tbub.setContent(url);
                                    tbub.setFileUrl(url);
                                }

                            } else if (imMessage.getType() == ChatGroupRecyclerAdapter.TO_USER_FILE) {//文件


                            } else if (imMessage.getType() == ChatGroupRecyclerAdapter.TO_USER_VOICE) {
                                String response = HttpAssist.uploadFile(new File(imMessage.getFilePath()), "", false);
                                ImageEntity imageEntity = gson.fromJson(response, ImageEntity.class);
                                String url = imageEntity.getData().getInfo().get(0);
                                String contentStr = ToolsUtils.voiceEntivityToStr(url, imMessage.getUserVoiceTime());
                                imMessage.setContent(contentStr);
                                imMessage.setFileUrl(url);
                                tbub.setContent(contentStr);
                                tbub.setFileUrl(url);
                                ChatGroupActivity.this.seconds = imMessage.getUserVoiceTime();
                                voiceFilePath = filePath;
                            } else if (imMessage.getType() == ChatGroupRecyclerAdapter.TO_USER_LOCATION) {//位置
                                String response = HttpAssist.uploadFile(new File(imMessage.getFilePath()), "", false);
                                ImageEntity imageEntity = gson.fromJson(response, ImageEntity.class);
                                String url = imageEntity.getData().getInfo().get(0);
                                String s = ToolsUtils.locationEntivityToStr(url, address, lat, lut);
                                if (null != response && response.contains("http")) {//上传成功 删除截图
                                    File imgfile = new File(imMessage.getFilePath());
                                    imgfile.delete();
                                }
                                imMessage.setContent(s);
                                imMessage.setFileUrl(url);
                                tbub.setContent(s);
                                tbub.setFileUrl(url);
                            } else if (imMessage.getType() == ChatRecyclerAdapter.TO_WITHDRAW_MSG) {//撤回消息
                                WithdrawEntity withdrawEntity = new WithdrawEntity();
                                withdrawEntity.setMsgid(sendmsgId);
                                String s = new Gson().toJson(withdrawEntity);
                                imMessage.setContent(s);//放入消息id
                                tbub.setContent(s);
                            }
                        } catch (Exception e) {
                            //没有网络时获取到的数据是错误的，不能使用gson转换
                            Log.e("", "");
                        }
                        mSocket = App.getInstance().getSocket();
                        retryCount++;
                        if (tblist.size() == 0) {//结束线程
                            imMessage.setSendState(Constant.SENDERROR);
                            imMessage.save();
                            return;
                        }
                        if (mSocket != null) {
                            mSocket.emit(Constant.EVENT, IMMessageToJson.changeJSONObject(imMessage), new Ack() {
                                @Override
                                public void call(Object... args) {
                                    imMessage.setSendState(Constant.COMPLETED);
                                    tbub.setSendState(Constant.COMPLETED);
                                    imMessage.save();
                                    sendMessageHandler.sendEmptyMessage(SEND_OK);
                                    sendState = true;
                                }
                            });
                        }
                        try {
                            Thread.sleep(Constant.SOCKET_SEND_TIME);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
    }


    /**
     * 接收文字
     */
    String content = "";

    private void receriveMsgText(final String content) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String message = getResources().getString(R.string.reply) + content;
                ImMessage tbub = new ImMessage();
                tbub.setContent(message);
                tbub.setType(ChatRecyclerAdapter.FROM_USER_MSG);
                tblist.add(tbub);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
            }
        }).start();
    }

    //阅后即焚
    @Override
    protected void sendReadDelete(File imgfile) {
        setSocket();
        long currentTime = System.currentTimeMillis();
        final ImMessage imMessage;

        imMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_READDELETE,
                "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_GROUP,
                destid, imgfile.getPath(), Constant.MESSAGE_TYPR_READ_DELETE,
                currentTime, System.currentTimeMillis(), 0, imgfile.getPath(), fromid + "__" + destid, 0, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        imageList.add(new ImageInfoBean(tblist.get(tblist.size() - 1).getFilePath(),true));
        imagePosition.put(tblist.size() - 1, imageList.size() - 1);
        imMessage.setSendState(Constant.SENDING);
        socketSend(imMessage, null, 0, 0);
    }

    /**
     * 发送图片
     */
    int i = 0;

    @Override
    protected void sendImage(final ImageSendEntity entity) {
        setSocket();
        long currentTime = System.currentTimeMillis();
        final ImMessage imMessage;

        imMessage = getTbub(Constant.VERSION_MESSAGE_CHART,
                Constant.DEV_TYPE,
                0,
                ChatRecyclerAdapter.TO_USER_IMG,
                "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_GROUP,
                destid,
                JSON.toJSONString(entity),
                Constant.MESSAGE_TYPR_IMAGE,
                currentTime,
                System.currentTimeMillis(),
                0,
                entity.getImagePath(),
                fromid + "__" + destid,
                0,
                userEntivity.getHeadUrl(),
                mGroupEntivity.getMarkName());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        imageList.add(new ImageInfoBean(tblist.get(tblist.size() - 1).getFilePath(),entity.isCanForward()));
        imagePosition.put(tblist.size() - 1, imageList.size() - 1);
        imMessage.setSendState(Constant.SENDING);
        socketSend(imMessage, null, 0, 0);

    }

    /**
     * 接收图片
     */
    String filePath = "";

    private void receriveImageText(final String filePath) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ImMessage tbub = new ImMessage();
                tbub.setType(ChatRecyclerAdapter.FROM_USER_IMG);
                tblist.add(tbub);
                imageList.add(new ImageInfoBean(tblist.get(tblist.size() - 1).getFileUrl(),true));
                imagePosition.put(tblist.size() - 1, imageList.size() - 1);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
            }
        }).start();
    }

    /**
     * 发送语音
     */
    @Override
    protected void sendVoice(final float seconds, final String filePath) {
        setSocket();
        long currentTime = System.currentTimeMillis();
        final ImMessage imMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0,
                ChatRecyclerAdapter.TO_USER_VOICE, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, destid, filePath, Constant.MESSAGE_TYPR_VOICE,
                currentTime, System.currentTimeMillis(), 0, filePath, fromid + "__" + destid, seconds, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        imMessage.setSendState(Constant.SENDING);
        socketSend(imMessage, null, 0, 0);

    }

    /**
     * 发送位置
     *
     * @param file
     * @param addr
     * @param lat
     * @param lut
     */
    @Override
    protected void sendLocation(File file, String addr, double lat, double lut) {
        setSocket();
        long currentTime = System.currentTimeMillis();
        final ImMessage imMessage;
        imMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_LOCATION,
                "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_GROUP,
                destid, file.getPath(), Constant.MESSAGE_TYPR_LOCATION,
                currentTime, System.currentTimeMillis(), 0, file.getPath(), fromid + "__" + destid, 0, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        imageList.add(new ImageInfoBean(tblist.get(tblist.size() - 1).getFileUrl(),true));
        imagePosition.put(tblist.size() - 1, imageList.size() - 1);
        imMessage.setSendState(Constant.SENDING);
        socketSend(imMessage, addr, lat, lut);
    }

    /**
     * 接收语音
     */
    float seconds = 0.0f;
    String voiceFilePath = "";

    private void receriveVoiceText(final float seconds, final String filePath) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ImMessage tbub = new ImMessage();
                tbub.setUserVoiceTime(seconds);
                tbub.setUserVoicePath(filePath);
                tbAdapter.unReadPosition.add(tblist.size() + "");
                tbub.setType(ChatRecyclerAdapter.FROM_USER_VOICE);
                tblist.add(tbub);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);

            }
        }).start();
    }

    private void newUserNameUpdateMSG(final ImMessage imMessage) {
        /****************************更新用户群昵称****************开始*********************/
        if (null != tblist && tblist.size() > 0) {
            for (int j = 0; j < tblist.size(); j++) {
                ImMessage imMessage22 = tblist.get(j);
                if (null != imMessage && null != imMessage22 && imMessage.getDestid().equals(imMessage22.getDestid())
                        && (!imMessage.getFromname().equals(imMessage22.getFromname())
                        || !imMessage22.getImageIconUrl().equals(imMessage.getImageIconUrl()))) {
                    imMessage22.setFromname(imMessage.getFromname());

                    tblist.set(j, imMessage22);

                }

            }
            /*
            把群公告remove掉，这样就不会在消息对话框里面显示
             */
            List<ImMessage> list = new ArrayList<>();
            list =tblist;
            for (int i = list.size()-1 ;i >= 0;i--){
                ImMessage msg = list.get(i);
                if (msg != null && msg.getMessageType() == Constant.MESSAGE_TYPR_CALL_OFFER){
                    tblist.remove(i);
                }
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    /**
                     * 更新界面
                     */
                    tbAdapter.notifyDataSetChanged();
                }
            });

        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class
                            , "belong_group_id=? and uid=?", new String[]{"" + imMessage.getFromid(), "" + imMessage.getDestid()});

                    if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
                        for (int j = 0; j < groupFriendEntivities.size(); j++) {
                            GroupFriendEntivity groupFriendEntivity = groupFriendEntivities.get(i);
                            if (null != groupFriendEntivity
//                                    && (""+groupFriendEntivity.getUid()).equals(""+imMessage.getDestid())
                                    && ((!"".equals(imMessage.getImageIconUrl()) && !imMessage.getImageIconUrl().equals(groupFriendEntivity.getHeadUrl()))
//                                    || !imMessage.getFromname().equals(groupFriendEntivity.getName())
                            )
                                    ) {
                                groupFriendEntivity.setHeadUrl(imMessage.getImageIconUrl());
                                groupFriendEntivity.save();
                            }
                        }
                    }

                    /**
                     * 更新好友信息
                     */
                    ImFriendEntivity idFriendsInfo = ImFriendEntivity.findById(ImFriendEntivity.class, imMessage.getDestid());
                    if (!"".equals(imMessage.getImageIconUrl()) && !imMessage.getImageIconUrl().equals(idFriendsInfo.getHeadUrl())) {
                        idFriendsInfo.setHeadUrl(imMessage.getImageIconUrl());
                        idFriendsInfo.save();//好友列表-个人信息
                    }

                    String uniqueness = fromid + "__" + destid;
                    final List<ImMessage> messageList = ImMessage.find(ImMessage.class, "uniqueness=? and  destid=?", new String[]{uniqueness, null == imMessage ? "" : "" + imMessage.getDestid()});

                    if (null != messageList && messageList.size() > 0) {
                        for (int j = 0; j < messageList.size(); j++) {
                            final int pos = j;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ImMessage imMessage22 = messageList.get(pos);
                                    Log.i(TAG, "onImMessageEvent: -----更新用户群昵称-----" + imMessage22.toString());
                                    if (null != imMessage && null != imMessage22 && imMessage.getDestid().equals(imMessage22.getDestid()) && !imMessage.getFromname().equals(imMessage22.getFromname())) {
                                        imMessage22.setFromname(imMessage.getFromname());
                                        if (!imMessage22.getImageIconUrl().equals(imMessage.getImageIconUrl())) {
                                            imMessage22.setImageIconUrl(imMessage.getImageIconUrl());
                                        }
                                        imMessage22.save();
                                    }
                                }
                            });
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        /****************************更新用户群昵称**************结束***********************/
    }

    //收到消息
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onImMessageEvent(final ImMessage imMessage) {
        Log.i(TAG, "onImMessageEvent: --1567--------------" + imMessage.toString());
       /* //如果是群公告在聊天信息直接不接收
        if ( imMessage.getFromType() == Constant.MESSAGE_TYPR_CALL_OFFER){
            return;
        }
*/
        if (imMessage.getFromType() != Constant.FROM_TYPE_GROUP) {
            //不是群不接受消息
            if (imMessage.getFromType() == Constant.FROM_TYPE_SYS) {//由于这两个服务器返回是系统消息，so...
                switch (imMessage.getMessageType()) {
                    case Constant.MESSAGE_TYPR_ADD_GROUP: {//有人加入群
                        tblist.add(imMessage);
                        sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                        List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and uid=?", "" + destid, "" + imMessage.getDestid());
                        if (null != groupFriendEntivities && groupFriendEntivities.size() > 0) {
                        } else
                            getUserById("" + imMessage.getDestid());
                        break;
                    }
                    case Constant.MESSAGE_TYPR_GROUP_SET_MANAGER:
                    case Constant.MESSAGE_TYPR_GROUP_CANCEL_MANAGER:
                        tblist.add(imMessage);
                        sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                        break;
                    /*case Constant.MESSAGE_TYPR_BYE_GROUP: {//有人退出
                        tblist.add(imMessage);
                        sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                        // groupFriendsNumber();
                        break;
                    }*/
                    case Constant.MESSAGE_TYPR_CALL_OFFER: //有群公告被发布
                        //Log.i(TAG, "onImMessageEvent: ------群公告有通知来了？？？？------------destid-" + destid);
                    case Constant.MESSAGE_TYPR_CALL_ANSWER: //有群公告被编辑
                        Log.i(TAG, "onImMessageEvent: ------群公告有通知来了？？？？------------destid-" + destid);
                        Log.i(TAG, "onImMessageEvent: ------群公告有通知来了？？？？-------------" + imMessage.toString());
                        if (("" + destid).equals("" + imMessage.getFromid())) {
                            imMessage.setPayed(false);
                            if (null != dialog && dialog.isShowing()) {
                                dialog.dismiss();
                            }
                            dialog = MyAlertDialogManages.initShowNoticed(ChatGroupActivity.this, imMessage, null);
                        }
                        break;
                    case Constant.NOTICE_OF_GROUP_OUT:
                        tblist.add(imMessage);
                        sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                        break;
                }
            } else {
                return;
            }
        }
        Log.i("info", "聊天界面接收到消息11111==" + imMessage.toString());
        if ((imMessage.getDestid() + "").equals(ToolsUtils.getMyUserId())) {

            switch (imMessage.getMessageType()) {
                case Constant.MESSAGE_TYPR_GROUP_CHANGE_UNAME:
                    //这里是用户群昵称修改
                    if (null != mGroupEntivity) {
                        mGroupEntivity.setMarkName(imMessage.getContent());
                        mGroupEntivity.save();
                    }
                    return;
                case Constant.MESSAGE_TYPR_GROUP_SET_MANAGER:
                case Constant.MESSAGE_TYPR_GROUP_CANCEL_MANAGER:
                    Log.i("info", "聊天界面接收到消息==0010==");
                    Log.i("info", "onMessage: ===55====" + imMessage.toString());

                    /*{id=null, version=0, devType=null, geoId=0, msgId=627c838c-36ce-41b6-8466-155768d9a174,
                    fromid=2373, fromname=123027, fromType=3, destid=17246, content={"role":2,"name":"123027"},
                    messageType=55, sendTime=1505368804251, receiveTime=0, status=0, userVoiceTime=0.0,
                     userVoicePath={"role":2,"name":"123027"}, userVoiceUrl=null, fileUrl={"role":2,"name":"123027"},
                      filePath=null, imageIconUrl=, uniqueness=null, type=0, sendState=0, content_fy=null, isShowFY=,
                      isRead=false, isPayed=false, isklopen=false}*/


                    return;
                case Constant.MESSAGE_TYPR_GROUP_BRIFE:
                    Log.i("info", "onMessage: ===56====" + imMessage.toString());
                    try {
                        ImGroupEntivity mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, imMessage.getFromid());
                        com.alibaba.fastjson.JSONObject json = JSON.parseObject(imMessage.getContent());
                        mImGroupEntivity.setDescriptions(json.getString("descriptions"));
                        mImGroupEntivity.save();
                        EventBus.getDefault().post(EventBusType.REFRESH_GROUP_BRIFE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                case Constant.NOTICE_OF_GROUP_OUT:
                    Log.i("info", "onMessage: ===64====" + imMessage.toString());
                    return;

            }

            tblist.add(imMessage);
            sendMessageHandler.sendEmptyMessage(SEND_OK);
            return;
        }
        Log.i("info", "聊天界面接收到消息==001==");
        if (imMessage.getFromid() != destid) {//不是当前群，不接受
            Log.i("info", "聊天界面接收到消息==002==");
            return;
        }
        //如果是群公告在聊天信息直接不接收
//        if ( imMessage.getMessageType() == Constant.MESSAGE_TYPR_CALL_OFFER){
//            return;
//        }

        newUserNameUpdateMSG(imMessage);
        Log.i("info", "聊天界面接收到消息==003==");
        switch (imMessage.getMessageType()) {
            case Constant.MESSAGE_TYPR_TEXT: {
                //Log.i("info","接收到文本消息"+imMessage.getContent());
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_MSG);
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_BQEMOJI: {
                // Log.i("info","这里接收到消息"+imMessage.toString());
                String content = imMessage.getContent();
                MsgEntity receirvemsg = new Gson().fromJson(content, MsgEntity.class);
                if (receirvemsg.getMsgCodes() != null && !"".equals(receirvemsg.getMsgCodes())) {
                    //大表情
                    imMessage.setType(ChatRecyclerAdapter.FROM_USER_EMOJI);
                } else {//
                   /* //图文混排
                   // Log.i("info","receirvemsg=="+receirvemsg.toString()+"  "+receirvemsg.getAiteId());
                    if (null != receirvemsg.getAiteId() && receirvemsg.getAiteId().size() > 0) {
                       // for (int i = 0; i < receirvemsg.getAiteId().size(); i++) {
                            Long aiteId = receirvemsg.getAiteId().get(0);
                      //  Log.i("info","真假=="+(""+aiteId).equals(ToolsUtils.getMyUserId()));
                            if ((""+aiteId).equals(ToolsUtils.getMyUserId())) {//这里艾特了你
                              //  Log.i("info","收到艾特消息");
                                tvAite.setVisibility(View.VISIBLE);
                            }
                     //   }
                    }*/
                    imMessage.setType(ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT);
                }
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_IMAGE: {
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_IMG);
                tblist.add(imMessage);
                imageList.add(new ImageInfoBean(tblist.get(tblist.size() - 1).getFileUrl(), IMMessageUtil.canImageForward(imMessage)));
                imagePosition.put(tblist.size() - 1, imageList.size() - 1);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }

            case Constant.MESSAGE_TYPR_VOICE: {
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_VOICE);
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                //      tbAdapter.unReadPosition.add(tblist.size() + "");
                break;
            }
            case Constant.MESSAGE_TYPR_REDPACKTE: {
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_LOCATION: {//接收到位置消息
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
            }
            break;
            case Constant.MESSAGE_TYPR_TRANSFRE: {
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_GET_REDPACKET: {
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_TRANSFRE_OK: {
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_TRANSFRE_BACK: {
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_REDPACKET_BACK: {
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_BYE_GROUP: {//有人退出群
                Log.i(TAG, "onImMessageEvent: getCreaterId=" + mGroupEntivity.getCreaterId() + "---myId=" + ToolsUtils.getMyUserId());
                if (null != mGroupEntivity && !("" + imMessage.getDestid()).equals("" + ToolsUtils.getMyUserId())) {
                    tblist.add(imMessage);
                    sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                } else {
                    imMessage.delete();
                }
                List<ImFriendEntivity> mFriendEntivities2 = new ArrayList<>();
                if (null != mFriendEntivities) {
                    for (int i = 0; i < mFriendEntivities.size(); i++) {
                        if (!("" + mFriendEntivities.get(i).getId()).equals("" + imMessage.getDestid())) {
                            mFriendEntivities2.add(mFriendEntivities.get(i));
                        } else {
                            ToolsUtils.deleteGroupUser(mFriendEntivities.get(i), destid);
                        }
                    }
                }
                mFriendEntivities.clear();
                mFriendEntivities.addAll(mFriendEntivities2);
                tbAdapter.setImFriendEntivity(mFriendEntivities);
                tbAdapter.notifyDataSetChanged();
                groupFriendsNumber();
                break;
            }
            case Constant.MESSAGE_TYPR_REDPACKET_NOFINISH: {
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_VEDIO:
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            case Constant.MESSAGE_TYPR_GROUP_CHANGE_UNAME: {//群成员昵称有修改，
                if (null != mFriendEntivities && mFriendEntivities.size() > 0) {
                    for (int i = 0; i < mFriendEntivities.size(); i++) {
                        if (("" + mFriendEntivities.get(i).getId()).equals("" + imMessage.getDestid())) {
                            ImFriendEntivity mmm = mFriendEntivities.get(i);
                            mmm.setMarkName(imMessage.getContent());
                            mFriendEntivities.set(i, mmm);
                        }
                    }
                    List<GroupFriendEntivity> groupUserSss = ToolsUtils.getGroupUserSss(mGroupEntivity.getId());
                    int size = groupUserSss.size();
                    for (int j = 0; j < size; j++) {
                        GroupFriendEntivity friendEntivity = groupUserSss.get(j);
                        if (("" + imMessage.getDestid()).equals(friendEntivity.getUid() + "")) {
                            // Log.e(TAG, "onImMessageEvent: 这里判定 两个ID 0---" + imMessage.getDestid() + "-----" + friendEntivity.getUid());
                            friendEntivity.setMarkName(imMessage.getContent());
                            friendEntivity.save();
                        }
                    }
                }
                long count = GroupFriendEntivity.count(GroupFriendEntivity.class, "belong_group_id=?", new String[]{"" + destid});
                /**
                 * 这里暂时将人数删除
                 */

                preTvTitle.setText(mGroupEntivity.getName() + "(" + count + ")");
//                preTvTitle.setText(mGroupEntivity.getName() );
                // preTvTitle.setText();
                tbAdapter.setImFriendEntivity(mFriendEntivities);
                tbAdapter.notifyDataSetChanged();
                break;
            }
            case Constant.MESSAGE_TYPR_WITHDRAW:
                //根据id 去删除对应的记录
                String content = imMessage.getContent();
                Log.i("info", "content=" + content);
                WithdrawEntity wd = new Gson().fromJson(content, WithdrawEntity.class);
                for (int q = 0; q < tblist.size(); q++) {//先从列表查询对应的消息
                    ImMessage imMessage1 = tblist.get(q);
                    Log.i("info", "撤回的id==" + imMessage1.getMsgId() + "---" + wd.getMsgid());
                    if (imMessage1.getMsgId().equals(wd.getMsgid())) {
                        tblist.remove(q);
                        imMessage1.delete();//从数据库删除
                        break;
                    }
                }
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            case Constant.MESSAGE_TYPR_FILE:
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_FILE);
                String content1 = imMessage.getContent();
                final FileMsgEntivity fileMsgEntivity = new Gson().fromJson(content1, FileMsgEntivity.class);
                tblist.add(imMessage);
                if (fileMsgEntivity != null) {
                    final String fileUrl = fileMsgEntivity.getFileUrl();//获取到文件下载路径
                    if (!ToolsUtils.isExsite(fileUrl)) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    String s1 = HttpAssist.fileDown(fileUrl, 1314, imMessage.getMsgId());//保存的本地路径
                                    fileMsgEntivity.setFilished(true);
                                    fileMsgEntivity.setFileUrl(s1);
                                    String s = new Gson().toJson(fileMsgEntivity);
                                    List<ImMessage> imMessages = ImMessage.find(ImMessage.class, "msg_id = ?", new String[]{imMessage.getMsgId()});
                                    if (imMessages != null && imMessages.size() > 0) {
                                        imMessages.get(0).setFilePath(s1);
                                        imMessages.get(0).setContent(s);
                                        imMessages.get(0).save();
                                    }
                                    imMessage.setFilePath(s1);
                                    imMessage.setContent(s);
                                /*ImMessage msg = imMessage;
                                ImMessage byId = ImMessage.findById(ImMessage.class, imMessage.getId());
                                byId.delete();
                                msg.save();*/
                                    sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                                } catch (Exception e) {

                                }
                            }
                        }).start();
                    } else {
                        fileMsgEntivity.setFilished(true);
                        String s = new Gson().toJson(fileMsgEntivity, FileMsgEntivity.class);
                        imMessage.setContent(s);
                    }
                }
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            case Constant.MESSAGE_TYPR_READ_DELETE:
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            case Constant.MESSAGE_TYPR_AAMONEY_GET://AA收款
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            case Constant.Someone_initiated_the_lucky_red_envelope://幸运红包
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            case Constant.MESSAGE_TYPR_FRIEND_HEAD: {//
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_FRIEND_MP);

                tblist.add(imMessage);

                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            /*case Constant.MESSAGE_TYPR_TRANSFOR_ISCOME:
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;*/
        }
        saveGroupFriendInfo(imMessage);
    }


    private void saveGroupFriendInfo(final ImMessage imMessage) {

        Log.i(TAG, "saveGroupFriendInfo: =============" + imMessage.getDestid());//发送人的ID
        Log.i(TAG, "saveGroupFriendInfo: =============" + imMessage.getFromid());


//        try {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    /**
//                     * 更新好友信息
//                     */
//                    ImFriendEntivity idFriendsInfo = ImFriendEntivity.findById(ImFriendEntivity.class, destid);
//                    if ((!"".equals(imMessage.getImageIconUrl()) && !imMessage.getImageIconUrl().equals(idFriendsInfo.getHeadUrl()))
//                            || !imMessage.getFromname().equals(idFriendsInfo.getName())){
//                        idFriendsInfo.setHeadUrl(imMessage.getImageIconUrl());
//                        idFriendsInfo.setName(imMessage.getFromname());
//                        idFriendsInfo.save();//好友列表-个人信息
//                    }
//
//                    boolean isHaveNo = false ;
//
//                    if (null!=tblist && tblist.size() > 0){
////            for (int j = 0; j < tblist.size(); j++) {
//                        int j = 0 ;
//                        for (ImMessage imMessageM :tblist) {
//                            if (imMessage.getFromid().equals(imMessageM.getFromid())) {
//                                if ((!"".equals(imMessage.getImageIconUrl()) && !imMessage.getImageIconUrl().equals(imMessageM.getImageIconUrl()))
//                                        || !imMessage.getFromname().equals(imMessageM.getFromname())){
//                                    friendheadurl = imMessage.getImageIconUrl();
//
//                                    imMessageM.setImageIconUrl(imMessage.getImageIconUrl());
//                                    imMessageM.setFromname(imMessage.getFromname());
////                        imMessageM.save();
//                                    tblist.set(j,imMessageM);
//
//                                    isHaveNo = true ;
//                                }
//                            }
//                            j++;
//                        }
//                    }
//                    if (isHaveNo){
//                        /**
//                         * 思来想去，这个地方还是拿出来吧
//                         * 强势一些，每次来都更新下，这样就可以只要有变化就全部更新
//                         */
//                        saveMessageAll(imMessage);
//
//                        //聊天列表-个人信息
//                        List<MessageEntivity> sysList3 = MessageEntivity.find(MessageEntivity.class, "uniqueness=? and fromid=? ", new String[]{ToolsUtils.getMyUserId()+"___",""+imMessage.getFromid()});
//                        if (null!=sysList3 && sysList3.size() > 0){
////                            for (int k = 0; k < sysList3.size(); k++) {
//                            MessageEntivity messageEntivity = sysList3.get(0);
//                            messageEntivity.setImgUrl(imMessage.getImageIconUrl());
//                            messageEntivity.setNick(imMessage.getFromname());
//                            messageEntivity.save();
////                            }
//                        }
//                        EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
//                    }
//
//                }
//            }).start();
//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }

    /**
     * 根据id查询用户详情，查询完成后保存数据库
     *
     * @param destid
     */
    private synchronized void getUserById(String destid) {
        String fromid = ToolsUtils.getMyUserId();
        mPgService.getUserById(fromid, destid).subscribe(new AbsAPICallback<ImFriendEntivity>() {
            @Override
            public void onNext(ImFriendEntivity mFriendEntivity) {
                if (null == mFriendEntivities) mFriendEntivities = new ArrayList<>();
                mFriendEntivities.add(mFriendEntivity);
                ToolsUtils.saveGroupUser(mFriendEntivity, mGroupEntivity.getId());
                tbAdapter.setImFriendEntivity(mFriendEntivities);
                tbAdapter.notifyDataSetChanged();
                groupFriendsNumber();
            }

            @Override
            protected void onResultError(ApiException ex) {
            }
        });
    }

    @Override
    protected void onDestroy() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//点了屏幕
        tblist.clear();
        tbAdapter.notifyDataSetChanged();
        wcLinearLayoutManger = null;
        sendMessageHandler.removeCallbacksAndMessages(null);
        if (myList.refreshHeader != null) {
            if (myList.refreshHeader.animator != null) {
                myList.refreshHeader.animator.cancel();
            }
        }
        if (MyAlertDialogManages.dlg != null) {
            MyAlertDialogManages.dlg.dismiss();
            MyAlertDialogManages.dlg = null;
        }
        firstTag = -1;
        v = null;
        myList.setheadNull();
        myList.removeAllHeaderViews();
        myList.removeAllFooterViews();
        audioManager = null;
        EventBus.getDefault().post(Constant.APP_DESTID_CHAT_ACTIVITY);
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (bqmm != null) {
            bqmm.destroy();
        }
    }

    @Override
    public void onStop() {
        EventBus.getDefault().post(Constant.STOP_VOICE_PLAY);

        clearMessage();
        App.destid = -1;
        super.onStop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPaystring(PayString code)//在ui线程执行
    {
        if (code != null) {
            String msgid = code.getMsgid();
            List<ImMessage> imMessages = ImMessage.find(ImMessage.class, "msg_id=?", new String[]{msgid});
            if (imMessages.size() > 0) {
                imMessages.get(0).setPayed(true);
                imMessages.get(0).save();
            }
            for (int i = 0; i < tblist.size(); i++) {
                if (tblist.get(i).getMsgId().equals(msgid)) {
                    tblist.get(i).setPayed(true);
                    tbAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    //AA收款(群)
    @Override
    protected void sendAAcollection(String nums, String money, String discrible, String amt) {
        String userId=ToolsUtils.getMyUserId();
        //要传给后台的参数全部封装成json，然后加密传给后台
        String destid1=Long.toString(destid);//把destid强转成string
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("counts", nums);
        json.put("destType", "2");
        json.put("destId", destid1);
        json.put("totalAmount", money);
        json.put("userId", userId);
        json.put("msg", discrible);
        String content = RequestRSAUtils.setRsaContent(json);
        mPgService.aaTrans(content).subscribe(new AbsAPICallback<AAentivity>() {
        //.aaTrans(nums, "" + destid, "2", discrible, money, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<AAentivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                showToast(getResources().getString(R.string.net_error));
            }

            @Override
            public void onNext(AAentivity aAentivity) {
                hideProgress();

                setSocket();
                String content = new Gson().toJson(aAentivity);
                //long currentTime = System.currentTimeMillis();
                final ImMessage imMessage = getTbub(0, 1, 0, ChatGroupRecyclerAdapter.TO_USER_AA, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, destid, content, Constant.MESSAGE_TYPR_AAMONEY_GET,
                        System.currentTimeMillis(), System.currentTimeMillis(), 0, null, fromid + "__" + destid, 0, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(SEND_OK);
                socketSend(imMessage, null, 0, 0);
            }
        });


    }

    @Override
    protected void findView() {
        super.findView();
        pullList.setSlideView(new PullToRefreshView(this).getSlideView(PullToRefreshView.RECYCLERVIEW));
        myList = (PullToRefreshRecyclerView) findViewById(R.id.pulltorefreshrecyclerview);
        activityRootView.addOnLayoutChangeListener(this);
        screenHeight = ContentUtils.getScreenHeight(this);
        //听筒与免提控制
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        speakerBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setSpeakerphoneOn(isspeakerphone);
            }
        });
        myList.setLoadingMoreEnabled(false);
        myList.setPullRefreshEnabled(true);
        myList.setPullToRefreshListener(new PullToRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        loadmoreMessage();
                    }
                }).start();


            }

            @Override
            public void onLoadMore() {

            }
        });

    }

    //切换听筒方法
    private void setSpeakerphoneOn(boolean on) {
        if (on) {
            audioManager.setSpeakerphoneOn(true);
            speakerBt.setImageDrawable(getResources().getDrawable(R.drawable.speaker_phone));
            isspeakerphone = false;
        } else {
            Log.i("info", "听筒切换");
            audioManager.setSpeakerphoneOn(false);//关闭扬声器
            // audioManager.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
            setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
            //把声音设定成Earpiece（听筒）出来，设定为正在通话中
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            speakerBt.setImageDrawable(getResources().getDrawable(R.drawable.speaker_nomarl));
            isspeakerphone = true;
        }
        // 听筒模式下设置为false
        // 设置成听筒模式
        //audioManager.setMode( AudioManager.MODE_IN_COMMUNICATION);
        // 设置为通话状态
        //setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
    }

    private void loadmoreMessage() {
        isDown = true;
        if (pagelist != null) {
            pagelist.clear();
        }
        String uniqueness = fromid + "__" + destid;
        //pagelist = ImMessage.find(ImMessage.class, "uniqueness=? and from_type=? ", new String[]{uniqueness,Constant.FROM_TYPE_GROUP+""}, "", "send_time asc", page * number + "," + number);
        pagelist = ImMessage.find(ImMessage.class, "uniqueness=?", new String[]{uniqueness}, "", "send_time asc", page * number + "," + number);

        position = pagelist.size();
        if (pagelist.size() != 0) {
            pagelist.addAll(tblist);
            tblist.clear();
            tblist.addAll(pagelist);
            if (null != tblist && tblist.size() > 0) {
                newUserNameUpdateMSG(tblist.get(tblist.size() - 1));
            }

            if (imageList != null) {
                imageList.clear();
            }
            if (imagePosition != null) {
                imagePosition.clear();
            }
            int key = 0;
            int position = 0;
            for (ImMessage cmb : pagelist) {
                if (cmb.getType() == ChatRecyclerAdapter.TO_USER_IMG) {//本机路径
                    if (null != cmb.getFilePath() && !StringUtils.isEmpty(cmb.getFilePath())) {
                        imageList.add(new ImageInfoBean(cmb.getFilePath(),IMMessageUtil.canImageForward(cmb)));
                        imagePosition.put(key, position);
                        position++;
                    } else {
                        ImageSendEntity sendEntity = JsonUtil.toObject(cmb.getContent(), ImageSendEntity.class);
                        if(sendEntity != null) {
                            imageList.add(new ImageInfoBean(sendEntity.getImagePath(),sendEntity.isCanForward()));
                            imagePosition.put(key, position);
                            position++;
                        }
                    }
                } else if (cmb.getType() == ChatRecyclerAdapter.FROM_USER_IMG) {
                    imageList.add(new ImageInfoBean(cmb.getFileUrl(),IMMessageUtil.canImageForward(cmb)));
                    imagePosition.put(key, position);
                    position++;
                }
                key++;
            }
            tbAdapter.setImageList(imageList);
            tbAdapter.setImagePosition(imagePosition);
            if (wcLinearLayoutManger != null) {
                visibPosition = wcLinearLayoutManger.findFirstVisibleItemPosition();
                v = myList.getChildAt(visibPosition);
            }
            sendMessageHandler.sendEmptyMessage(PULL_TO_REFRESH_DOWN);
            if (page == 0) {
                pullList.refreshComplete();
                pullList.setPullGone();
                myList.setPullRefreshEnabled(false);
            } else {
                pullList.setPull();
                myList.setPullRefreshEnabled(true);
                page--;
            }
        } else {
            if (page == 0) {
                pullList.refreshComplete();
                pullList.setPullGone();
                myList.setPullRefreshEnabled(false);
            }
        }
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

    }

    @OnClick({R.id.pre_v_back, R.id.right, R.id.tv_aite, R.id.linear_bottom_kl, R.id.txt_nospick, R.id.level_clean, R.id.level_ok,R.id.vip_ok,R.id.vip_clean,R.id.vip_ok1,R.id.vip_clean1,R.id.vip_ok_expired,R.id.level_clean1})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back: {
                ActivityUtil.closeSoftKeyboard(this);
                this.finish();
                break;
            }
            case R.id.right: {   //群组信息
                Bundle bundle = new Bundle();
                bundle.putSerializable("groupSeri", mGroupEntivity);
                bundle.putLong("groupid", destid);
                startActivity(ChatGroupMgrActivity.class, bundle);
                break;
            }
            /*case R.id.red_packet:
                Bundle bundler = new Bundle();
                bundler.putLong("destid", destid);
                startActivityForResult(SendRedPackageGroupActivity.class,RESULT_RED_PACKET_SEND, bundler);
                break;
            */
            case R.id.tv_aite://艾特按钮
                /*if (tvAite.isPressed()){
                    tvAite.setElevation((float) ScreenUtil.dp2px(1));
                }
               // tvAite.setTranslationZ();
                tvAite.setElevation((float) ScreenUtil.dp2px(3));*/
                break;
            case R.id.linear_bottom_kl: {//口令点击
                String commant = txt_kl_content.getText().toString();
                if (null != commant && !"".equals(commant)) {
                    mEditTextContent.setText(commant);
                }
                linear_bottom_kl.setVisibility(View.GONE);
                break;
            }
            case R.id.txt_nospick://

                break;
            case R.id.level_clean://
                finish();
                break;
            case R.id.level_clean1://
                finish();
                break;
            case R.id.level_ok://
                ImGroupEntivity mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, destid);
                if (("" + mImGroupEntivity.getCreaterId()).equals(ToolsUtils.getMyUserId())) {//我是群主
                    GroupLevelSelectActivity.start(ChatGroupActivity.this, "" + destid, 1);
                    finish();
                } else {
                    finish();
                }
                break;
            case R.id.vip_ok1://
                ImGroupEntivity mImGroupEntivity1 = ImGroupEntivity.findById(ImGroupEntivity.class, destid);
                if (("" + mImGroupEntivity1.getCreaterId()).equals(ToolsUtils.getMyUserId())) {//我是群主
                    GroupLevelSelectActivity.start(ChatGroupActivity.this, "" + destid, 1);
                    finish();
                } else {
                    finish();
                }
                break;
            case R.id.vip_clean1://
                relativeVipOutOfDate1.setVisibility(View.GONE);
                break;
            case R.id.vip_ok://群成员对还有三天的续费

                DialogUtils.showPayDialog(this, new DialogUtils.ResultCallback<String>() {
                    @Override
                    public void onGetResult(String result) {

                        PGService.getInstance().getNetApi().payForGroupRenew(result,String.valueOf(destid),ToolsUtils.getMyUserId())
                                .compose(RxJavaUtil.<ValidateEntivity>applySchedules())
                                .compose(ChatGroupActivity.this.<ValidateEntivity>bindLifeCycle())
                                .compose(ChatGroupActivity.this.<ValidateEntivity>applyProgress("付费中..."))
                                .subscribe(new AbsAPICallback<ValidateEntivity>() {
                                    @Override
                                    public void onNext(ValidateEntivity validateEntivity) {
                                        showToast(validateEntivity.getInfo());
                                        relativeVipOutOfDate.setVisibility(View.GONE);
                                        getGroupMember(destid, fromid);

                                        int GroupSetupTime=Integer.parseInt(groupFriendEntivity.getDays())*24*60*60*1000;
//                                        Log.i("info1","GroupSetupTime11::::"+GroupSetupTime+"------"+destid+"-----"+fromid);
                                        Long data=GroupSetupTime+System.currentTimeMillis();
                                        Log.i("info1","data11:"+data);
                                        groupFriendEntivity.setGroupExpire(String.valueOf(data));
                                        Log.i("info1","新的时间存进去了");
                                        EventBus.getDefault().post(groupFriendEntivity);


                                    }
                                    @Override
                                    protected void onResultError(ApiException ex) {
                                        showToast(ex.getErrorInfo());
                                    }
                                });
                    }
                });
                break;
            case R.id.vip_ok_expired://群成员到期的续费
                //test 暂时写在这里
                /*msgDialog.setDialogSize(300,300);
                msgDialog.show();*/

                DialogUtils.showPayDialog(this, new DialogUtils.ResultCallback<String>() {
                    @Override
                    public void onGetResult(String result) {

                        PGService.getInstance().getNetApi().payForGroupRenew(result,String.valueOf(destid),ToolsUtils.getMyUserId())
                                .compose(RxJavaUtil.<ValidateEntivity>applySchedules())
                                .compose(ChatGroupActivity.this.<ValidateEntivity>bindLifeCycle())
                                .compose(ChatGroupActivity.this.<ValidateEntivity>applyProgress("付费中..."))
                                .subscribe(new AbsAPICallback<ValidateEntivity>() {
                                    @Override
                                    public void onNext(ValidateEntivity validateEntivity) {
                                        showToast(validateEntivity.getInfo());
                                        group_membership_has_expired.setVisibility(View.GONE);
                                        getGroupMember(destid, fromid);

                                        int GroupSetupTime=Integer.parseInt(groupFriendEntivity.getDays())*86400000;//转成时间磋
                                        Log.i("info1","GroupSetupTime11::::"+GroupSetupTime+"------"+destid+"-----"+fromid);
                                        Long data=GroupSetupTime+System.currentTimeMillis();
                                        Log.i("info1","data11:"+data);
                                        groupFriendEntivity.setGroupExpire(String.valueOf(data));
                                        Log.i("info1","新的时间存进去了");
                                        EventBus.getDefault().post(groupFriendEntivity);
                                    }
                                    protected void onResultError(ApiException ex) {
                                       showToast(ex.getErrorInfo());
                                   }
                                });
                   }
                });
                break;
            case R.id.vip_clean:
                relativeVipOutOfDate.setVisibility(View.GONE);
                break;
        }
    }

    /***
     *
     * 全局变量
     */
    List<GroupFriendEntivity> groupFriendEntivities = null;
    GroupFriendEntivity groupFriendEntivity = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_RED_PACKET_SEND:
                if (resultCode == 10) {
         /*           String destid = data.getStringExtra("destid");
                   String money = data.getStringExtra("money");
                   String liuyan = data.getStringExtra("liuyan");
                    String num = data.getStringExtra("num");
                   int sendType = data.getIntExtra("sendType",0);
                   String redPacketId = data.getStringExtra("redPacketId");
                   *//*final ImMessage imMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0,
                           ChatRecyclerAdapter.TO_USER_VOICE, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                           Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, destid, filePath, Constant.MESSAGE_TYPR_VOICE,
                           currentTime, System.currentTimeMillis(), 0, filePath, fromid + "__" + destid, seconds, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());*//*
                    ImMessage imMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0,
                            ChatRecyclerAdapter.TO_USER_REDPACKET, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                            Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, Long.parseLong(destid), "{\"redPacketId\":\"" + redPacketId + "\",\"msg\":\"" + liuyan + "\"}",
                            Constant.MESSAGE_TYPR_REDPACKTE,
                           System.currentTimeMillis(), System.currentTimeMillis(), 0, filePath, fromid + "__" + destid, 0,userEntivity.getHeadUrl(),mGroupEntivity.getMarkName());
                   tblist.add(imMessage);
                   imMessage.save();
                   sendMessageHandler.sendEmptyMessage(RECERIVE_OK);*/
                }
                break;
            case REQUST_SENDTOFRIEND://转发消息
                if (resultCode == REQUST_SENDTOFRIEND) {
//                if (resultCode == AITE_FRIENDS) {

//                    Intent intent = new Intent(ChatGroupActivity.this, ChatActivity.class);
//                    intent.putExtra("destid","");
//                    intent.putExtra("msg","");
//                    startActivity(intent);

                    scrollToFinishActivity();
                }
                break;
            case AITE_FRIENDS://
                if (resultCode == AITE_FRIENDS) {
                    friendname = data.getStringExtra("friendname");
                    friendids.add(data.getLongExtra("friendid", 0));
                    Log.i("info", "name===" + friendname + "  id==" + friendids.get(0));
                    String nnn = (null == friendname || "".equals(friendname)) ? "" + data.getLongExtra("friendid", 0) : friendname;
                    mEditTextContent.append(nnn + " ");
                }
                break;
            case RESULT_SEND_FILE:
               /* if (resultCode ==RESULT_OK){
                    Uri uri = data.getData();
                    try {
                        String realFilePath = ToolsUtils.getRealFilePath(this, uri);
                        Log.i("info","拿到的文件=="+realFilePath);
                        sendFile(realFilePath);
                        //File file = new File(realFilePath);
                    }catch (Exception e){

                    }
                }*/
                break;
            case SMALL_VEDIO://
                if (resultCode == RESULT_OK)
                    try {
                        String filePath = data.getStringExtra("videoUrl");
                        Log.e("lzf_video", filePath);
                        if (filePath != null && !filePath.equals("")) {
                            if (filePath.startsWith("file://")) {
                                filePath = data.getStringExtra("videoUrl").substring(7, filePath.length());
                            }
                            int duration = 0;
                            Log.i("info", "视频保存在：" + filePath);
                            //String[] split = filePath.split("/");
                            MediaMetadataRetriever media = new MediaMetadataRetriever();
                            media.setDataSource(filePath);
                            Bitmap bitmap = media.getFrameAtTime();
                            filePath.substring(0, filePath.lastIndexOf("/"));
                            String imgname = System.currentTimeMillis() + ".jpg";
                              /*  String urlpath = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/easyimVideo/" + imgname;*/
                            String urlpath = Environment.getExternalStorageDirectory() + "/" + imgname;
                            try {
                                duration = Integer.parseInt(media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            File f = new File(urlpath);
                               /* File f = new File(Environment
                                        .getDownloadCacheDirectory().getPath()+ "/easyimVideo/", imgname);*/
                            if (f.exists()) {
                                f.delete();
                            }
                            try {
                                FileOutputStream out = new FileOutputStream(f);
                                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                                out.flush();
                                out.close();
                                //Log.i(TAG, "已经保存");
                                VedioEntity vedioEntity = new VedioEntity();
                                vedioEntity.setVedioPath(filePath);
                                vedioEntity.setVedioSize(duration);
                                vedioEntity.setCanForward(true);
                                vedioEntity.setVedioBitmappath(urlpath);
                                sendVedio(vedioEntity);
                            } catch (FileNotFoundException e) {
                                showToast(getResources().getString(R.string.sp_hetpath_fail));
                                e.printStackTrace();
                            } catch (IOException e) {
                                showToast(getResources().getString(R.string.sp_hetpath_fail));
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception ex) {

                    }
                break;
            case ChatBottomViews.FROM_COLACTION:
                if (resultCode == 112211) {
                    ImMessage imessage = (ImMessage) data.getSerializableExtra("imessage");
                    if (imessage != null) {
                        setSocket();
                        tblist.add(imessage);
                        Log.i("info", "发送的消息为==" + imessage.toString());
                        sendMessageHandler.sendEmptyMessage(SEND_OK);
                        socketSend(imessage, null, 0, 0);
                    }
                }
                break;
            case ChatBottomViews.FROM_FRIENDMP:
                if (resultCode == 10) {
                    String name = data.getStringExtra("friendname");
                    String id = data.getStringExtra("friendid");
                    String head = data.getStringExtra("headurl");
                    ImMessage imMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0,
//                            ChatRecyclerAdapter.TO_USER_FRIEND_MP, UUID.randomUUID().toString(),
                            ChatRecyclerAdapter.TO_USER_FRIEND_MP, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                            Long.parseLong(null == fromid ? "0" : ("".equals(fromid) ? "0" : fromid)), Constant.FROM_TYPE_GROUP, destid,
                            "{\"contactId\":\"" + id + "\",\"headUrl\":\"" + head + "\",\"nickName\":\"" + name + "\"}",
                            Constant.MESSAGE_TYPR_FRIEND_HEAD,
                            System.currentTimeMillis(), System.currentTimeMillis(), 0, "", fromid + "_" + destid, 0,
                            userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());

                    if (imMessage != null) {
                        setSocket();
                        tblist.add(imMessage);
                        Log.i("info", "发送的消息为==" + imMessage.toString());
                        sendMessageHandler.sendEmptyMessage(SEND_OK);
                        socketSend(imMessage, null, 0, 0);
                    }
                }
                break;
            case ChatActivity.RESULT_TRANSFER_SEND:
                tbbv.setVisibility(View.GONE);
                mess_iv.setImageResource(R.drawable.tb_more);
                if (resultCode == 10) {
                    TransfreCreateEntivity transfreCreate = (TransfreCreateEntivity) data.getSerializableExtra("transfreCreate");
                    ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_TRANSFER, uuid, Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, destid,
                            "{\"transId\":\"" + transfreCreate.getId() + "\",\"msg\":\"" + transfreCreate.getMsg() + "\",\"amount\":\"" + transfreCreate.getAmount() + "\"}", Constant.MESSAGE_TYPR_TRANSFRE,
                            System.currentTimeMillis(), System.currentTimeMillis(), 0, "", fromid + "__" + destid, 0, userEntivity.getHeadUrl());
                    tblist.add(imMessage);
                    imMessage.save();
                    IMMessageToJson.ImMessageToMessageEntivity(imMessage, Constant.FROM_TYPE_SELF);
                    sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                }
                break;
//            case RESULT_TRANSFER_GET:
//                if (resultCode == 10) {
//                    TransferViewEntivity transfreCreate = (TransferViewEntivity) data.getSerializableExtra("TransferViewEntivity");
//
//                    ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_TRANSFER_OTHER_GET, uuid, Long.parseLong(null == transFromId ? "0" : ("".equals(transFromId) ? "0" : transFromId)), Constant.FROM_TYPE_MAM, Long.parseLong(null == transFromId ? "0" : ("".equals(transFromId) ? "0" : transFromId)),
//                            "{\"transId\":\"" + transfreCreate.getId() + "\",\"msg\":\"" + transfreCreate.getMsg() + "\",\"amount\":\"" + transfreCreate.getAmount() + "\"}", Constant.MESSAGE_TYPR_TRANSFRE_OK,
//                            System.currentTimeMillis(), System.currentTimeMillis(), 0, "", fromid + "_" + transFromId, 0, userEntivity.getHeadUrl());
////                    tblist.add(imMessage);
//                    imMessage.save();
//                    IMMessageToJson.ImMessageToMessageEntivity(imMessage, Constant.FROM_TYPE_SELF);
////                    sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
//                }
//                break;
        }
    }

    /**
     * 接收上传的速度
     *
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void oncommitLenght(FileProEtivity lenth) {
        Log.i("info", "上传的速度==" + lenth.getCommitsize());
        tbAdapter.setProgressint(lenth.getCommitsize(), lenth.getLenth(), lenth.getMsgID());
    }

    /**
     * 发送文件
     *
     * @param
     */
    @Override
    protected void sendFile(final String filepath) {
        setSocket();
        fileMsgEntivity = new FileMsgEntivity();
        InputStream is = null;
        String[] split = filepath.split("/");
        String filename = split[split.length - 1];//文件名
        fileMsgEntivity.setFileName(filename);
        try {
            is = new FileInputStream(new File(filepath));
            int available = is.available();//文件大小
            float i = (float) available / 1024 / 1024;
            DecimalFormat df = new DecimalFormat("0.00");
            String format = df.format(i);
            fileMsgEntivity.setFileSize(format + "MB");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String content = new Gson().toJson(fileMsgEntivity);
        long currentTime = System.currentTimeMillis();
        // Log.i("info", "fromid==" + fromid + "   destid==" + destid);
        final ImMessage fileimMessage = getTbub(0, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_FILE, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, destid, content, Constant.MESSAGE_TYPR_FILE,
                currentTime, System.currentTimeMillis(), 0, filepath, fromid + "__" + destid, 0, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());
        tblist.add(fileimMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String fileurl = HttpAssist.uploadFile(new File(filepath), fileimMessage.getMsgId(), true);//上传文件
                if (null != fileurl && !fileurl.equals("0") && !fileurl.equals("")) {
                    if (fileurl.contains("服务器异常")) {
                       /* Looper.prepare();
                        showToast("服务器异常，文件发送失败");
                        tblist.remove(tblist.size()-1);
                        Log.i("info","服务器异常，文件发送失败");*/
                        sendMessageHandler.sendEmptyMessage(UP_ERROR);
                        return;
                    }
                    try {
                        ImageEntity imageEntity = new Gson().fromJson(fileurl, ImageEntity.class);
                        fileMsgEntivity.setFileUrl(imageEntity.getData().getInfo().get(0));
                        fileMsgEntivity.setFilished(true);
                        Message msg = new Message();
                        msg.what = COMMIT_FINISH;
                        msg.obj = fileimMessage;
                        sendMessageHandler.sendMessage(msg);
                    } catch (Exception e) {

                    }

                } else {
                    showToast(getResources().getString(R.string.send_faild));//发送失败
                    fileimMessage.setSendState(Constant.SENDERROR);
                    sendMessageHandler.sendEmptyMessage(SEND_OK);
                }
            }
        }).start();
    }

    private void setSocket() {
        mSocket = App.socket;
        if (mSocket == null | !mSocket.connected()) {
            EventBus.getDefault().post(Constant.NOT_NET_SERVICE);
            String savesocketstr = ToolsUtils.savesocketstr(this, "", "", 2);
            String[] split = savesocketstr.split("___");
            App.initSocket(split[0], split[1]);
        }
    }

    /**
     * 查询群组好友列表
     */
    private void getGroupMember(String groupId, String fromid) {
        mPgService.getGroupMember(groupId, fromid).subscribe(new AbsAPICallback<SearchUserEntity>() {
            @Override
            public void onNext(SearchUserEntity friendEntivity) {
//                showToast("获取群成员列表成功！");
                mFriendEntivities = friendEntivity.getInfo();
                ToolsUtils.saveGroupUserS(mFriendEntivities, destid);
                tbAdapter.setImFriendEntivity(mFriendEntivities);
                tbAdapter.notifyDataSetChanged();
                tvTitle.setText(mGroupEntivity.getName() + "(" + (null == mFriendEntivities ? 0 : mFriendEntivities.size()) + ")");

            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    /**
     * 翻译
     */
    //	appid+q+salt+密钥 的MD5值
    private String getMd5Text(String q) {
        String dengStr = PGApi.BDFY_APP_ID + q + ToolsUtils.getMyUserId() + PGApi.BDFY_MY;
        return MD5.MD532(dengStr);
    }

    private void getFanYi(String str, final int type) {
        if (!ToolsUtils.currentNetState(this)) {//当前网络不可用
            return;
        }
        String biao = Locale.getDefault().getLanguage();
        if (biao.equals("zh")) {
            biao = biao + Locale.getDefault().getCountry();
        }

        mPgService.getTextFanYi(str, "auto", ToolsUtils.getMyFanYiMap().get(biao), PGApi.BDFY_APP_ID, ToolsUtils.getMyUserId(), getMd5Text(str)).subscribe(new AbsAPICallback<FanYiBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(FanYiBean data) {
                Log.i(TAG, "onNext: fanyi=" + data);

                ImMessage imm = tblist.get(type);
                imm.setContent_fy(new Gson().toJson(data));
                imm.setIsShowFY("1");
                tblist.set(type, imm);
                sendMessageHandler.sendEmptyMessage(REFRESH_FANYI);

            }
        });
    }

    public void doRainRed() {

        red0.setVisibility(View.VISIBLE);
        red1.setVisibility(View.VISIBLE);
        red2.setVisibility(View.VISIBLE);
        red3.setVisibility(View.VISIBLE);
        red4.setVisibility(View.VISIBLE);
        red5.setVisibility(View.VISIBLE);
        red6.setVisibility(View.VISIBLE);
        red7.setVisibility(View.VISIBLE);
        red8.setVisibility(View.VISIBLE);
        red9.setVisibility(View.VISIBLE);
        red10.setVisibility(View.VISIBLE);
        red11.setVisibility(View.VISIBLE);
        red12.setVisibility(View.VISIBLE);
        red13.setVisibility(View.VISIBLE);

        shuxingSet(red0, 5100, 120, 700);
        shuxingSet(red1, 2800, 110, 300);
        shuxingSet(red2, 3900, 80, 500);
        shuxingSet(red3, 2800, 50, 380);
        shuxingSet(red4, 4600, -70, 400);
        shuxingSet(red5, 3800, -120, 700);
        shuxingSet(red6, 5800, -70, 3300);
        handler.sendEmptyMessageDelayed(0x100, 1500);
    }

    public void doCancelRain() {
        handler.removeMessages(0x100);
        handler.removeMessages(0x110);
        red0.setVisibility(View.GONE);
        red1.setVisibility(View.GONE);
        red2.setVisibility(View.GONE);
        red3.setVisibility(View.GONE);
        red4.setVisibility(View.GONE);
        red5.setVisibility(View.GONE);
        red6.setVisibility(View.GONE);
        red7.setVisibility(View.GONE);
        red8.setVisibility(View.GONE);
        red9.setVisibility(View.GONE);
        red10.setVisibility(View.GONE);
        red11.setVisibility(View.GONE);
        red12.setVisibility(View.GONE);
        red13.setVisibility(View.GONE);
    }


    public void shuxingSet(View view, int time, float trX, float raZ) {

        set = new AnimatorSet();
        ObjectAnimator taX = ObjectAnimator.ofFloat(view, "translationX", 0, trX);
        ObjectAnimator taY = ObjectAnimator.ofFloat(view, "translationY", 0, height + 100f);
        ObjectAnimator ra = ObjectAnimator.ofFloat(view, "rotation", 0, raZ);


        set.setDuration(time);
        set.play(taY).with(taX).with(ra);
        set.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        App.destid = destid;
        initBQmm();//表情云
        getNoReadNotice();
        initRedKLMessage();
        updateMySpeakState();
        getGroupLevelState();
        updateFeeOutOfDateState();

        updateFeeOutOfDateState1();

        setChatBG();
    }


    private void setChatBG() {
        try {
            List<BGchat> bGchatList = BGchat.find(BGchat.class, "creatid=? and sessionid=?", new String[]{ToolsUtils.getMyUserId(), "" + destid});

            if (null != bGchatList && bGchatList.size() > 0) {
                BGchat bGchat = bGchatList.get(0);
                if ("".equals(bGchat.getBgchat())) {//单聊，默认
                    setChatBGAll();
                } else {//单聊，自己的设置
//                    Bitmap bitmap = PictureUtil.getSmallBitmap(choesimgpath);
                    Bitmap bitmap = BitmapFactory.decodeFile(bGchat.getBgchat(), new BitmapFactory.Options());
                    ivChatBackground.setBackground(new BitmapDrawable(bitmap));
                }
            } else {//单聊，未设置
                setChatBGAll();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setChatBGAll() {
        try {
            List<BGsetAll> bGchatList = BGsetAll.find(BGsetAll.class, "creatid=?", new String[]{ToolsUtils.getMyUserId()});

            if (null != bGchatList && bGchatList.size() > 0) {
                BGsetAll bGchat = bGchatList.get(0);
                if ("".equals(bGchat.getBgpath())) {//默认
                    ivChatBackground.setBackgroundColor(getResources().getColor(R.color.background));
                } else {//自己的设置
//                    Bitmap bitmap = PictureUtil.getSmallBitmap(choesimgpath);
                    Bitmap bitmap = BitmapFactory.decodeFile(bGchat.getBgpath(), new BitmapFactory.Options());
                    ivChatBackground.setBackground(new BitmapDrawable(bitmap));
                }
            } else {//未设置
                ivChatBackground.setBackgroundColor(getResources().getColor(R.color.background));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initRedKLMessage() {
//        mRedMessages
        mRedMessages.clear();
        List<ImMessage> imMessageList = ImMessage.find(ImMessage.class, "uniqueness=? and message_type=? and isklopen=?", new String[]{fromid + "_" + destid, "" + Constant.MESSAGE_TYPR_REDPACKTE, "false"},
                null, "send_time desc", " 0, 200");
        if (null != imMessageList && imMessageList.size() > 0) {
            for (int j = 0; j < imMessageList.size(); j++) {
                ImMessage imMessage = imMessageList.get(j);
                if (null == imMessage) continue;
                try {
                    RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
                    if (null != redPacketEntivity && null != redPacketEntivity.getRedPacketType()
                            && "3".equals(redPacketEntivity.getRedPacketType())) {
                        mRedMessages.add(imMessage);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initRedKLOpenFns(final String uid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mredPacketImMessage = null;
                List<ImMessage> imMessageList = ImMessage.find(ImMessage.class, "uniqueness=? and message_type=? and isklopen=?", new String[]{fromid + "_" + destid, "" + Constant.MESSAGE_TYPR_REDPACKTE, "false"},
                        null, "send_time asc", " 0, 200");
                if (null != imMessageList && imMessageList.size() > 0) {
                    for (int j = 0; j < imMessageList.size(); j++) {
                        ImMessage imMessage = imMessageList.get(j);
                        if (null == imMessage) continue;
                        try {
                            RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
                            if (null != redPacketEntivity
                                    && uid.equals("" + redPacketEntivity.getRedPacketId())) {
                                imMessage.setIsklopen(true);
                                imMessage.save();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (null != mRedMessages && mRedMessages.size() > 0) {
                    try {
                        int j = 0;
                        for (ImMessage imMessage : mRedMessages) {
                            if (null != imMessage) {
                                RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
                                if (null != redPacketEntivity) {
                                    if (uid.equals("" + redPacketEntivity.getRedPacketId())) {
                                        mRedMessages.remove(j);
                                        return;
                                    }
                                }
                            }
                            j++;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }


    private void openklRed(String content) {
        if (null != mredPacketImMessage) {//点击自动发送口令
            try {
                RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(mredPacketImMessage.getContent());
                if (null != redPacketEntivity) {
                    if (content.equals(redPacketEntivity.getCommand())) {
                        openRedPacket("" + redPacketEntivity.getRedPacketId());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.i("wgdinfo", "openklRed: ---------------05--------------");
            if (null != mRedMessages && mRedMessages.size() > 0) {
                try {
                    Log.i("wgdinfo", "openklRed: ---------06--------------------");
                    for (ImMessage imMessage : mRedMessages) {
                        Log.i("wgdinfo", "openklRed: --------07---------------------");
                        if (null != imMessage) {
                            RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
                            if (null != redPacketEntivity) {
                                Log.i("wgdinfo", "openklRed: ----------08-------------------");
                                if (content.equals(redPacketEntivity.getCommand())) {
                                    Log.i("wgdinfo", "openklRed: ----------09-------------------");
                                    openRedPacket("" + redPacketEntivity.getRedPacketId());
                                    return;
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.i("wgdinfo", "openklRed: ---------10--------------------");
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param view
     * @param withdraw 是否可以撤回
     */
    public void initMenu(View view, final boolean withdraw, final int type,boolean canForward) {

        popupMenu = new PopupMenu(this, view);
        menu = popupMenu.getMenu();
        // 通过XML文件添加菜单项
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.popup_menu_chat, menu);
        MenuItem item = menu.getItem(2);
        if (withdraw) {
            item.setTitle(getResources().getString(R.string.withdraws)); //这里对消息进行判断  是否可以撤回
        } else {
            item.setTitle(getResources().getString(R.string.delete));
        }
        switch (type) {
            case ChatRecyclerAdapter.TO_USER_VOICE:
            case ChatRecyclerAdapter.FROM_USER_VOICE:
                if (isspeakerphone) { //听筒
                    menu.getItem(0).setTitle(getResources().getString(R.string.goto_mt));
                } else {
                    menu.getItem(0).setTitle(getResources().getString(R.string.goto_tt));
                }
                break;
            case ChatRecyclerAdapter.TO_USER_EMOJI:
            case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
            case ChatRecyclerAdapter.FROM_USER_EMOJI:
            case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
//                menu.add("复制");
                menu.getItem(3).setTitle(getResources().getString(R.string.copy));

                break;
        }
        switch (type) {
            case ChatRecyclerAdapter.TO_USER_LOCATION:
            case ChatRecyclerAdapter.FROM_USER_LOCATION:
            case ChatRecyclerAdapter.TO_USER_IMG:
            case ChatRecyclerAdapter.FROM_USER_IMG:
            case ChatRecyclerAdapter.TO_USER_MSG:
            case ChatRecyclerAdapter.FROM_USER_MSG:
            case ChatRecyclerAdapter.FROM_USER_EMOJI:
            case ChatRecyclerAdapter.TO_USER_EMOJI:
            case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
            case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
            case ChatRecyclerAdapter.FROM_USER_FILE:
            case ChatRecyclerAdapter.FROM_USER_VEDIO:
            case ChatRecyclerAdapter.TO_USER_FILE:
            case ChatRecyclerAdapter.TO_USER_VEDIO:
                menu.getItem(0).setVisible(canForward);
                menu.getItem(1).setVisible(canForward);
                break;
        }
        popupMenu.show();
        // 监听事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.add_contacts://发给朋友
                        switch (type) {
                            case ChatRecyclerAdapter.TO_USER_VOICE:
                            case ChatRecyclerAdapter.FROM_USER_VOICE:
                                if (isspeakerphone) { //听筒
                                    audioManager.setSpeakerphoneOn(true);
                                    isspeakerphone = false;
                                    showToast(getResources().getString(R.string.goto_tt));
                                } else {
                                    audioManager.setSpeakerphoneOn(false);//关闭扬声器
                                    // audioManager.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
                                    setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
                                    //把声音设定成Earpiece（听筒）出来，设定为正在通话中
                                    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                                    speakerBt.setImageDrawable(getResources().getDrawable(R.drawable.speaker_nomarl));
                                    isspeakerphone = true;
                                    showToast(getResources().getString(R.string.goto_mt));
                                }
                                break;
                            case ChatRecyclerAdapter.TO_USER_LOCATION:
                            case ChatRecyclerAdapter.FROM_USER_LOCATION:
                            case ChatRecyclerAdapter.TO_USER_IMG:
                            case ChatRecyclerAdapter.FROM_USER_IMG:
                            case ChatRecyclerAdapter.TO_USER_MSG:
                            case ChatRecyclerAdapter.FROM_USER_MSG:
                            case ChatRecyclerAdapter.FROM_USER_EMOJI:
                            case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
                            case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
                            case ChatRecyclerAdapter.TO_USER_EMOJI:
                            case ChatRecyclerAdapter.FROM_USER_FILE:
                            case ChatRecyclerAdapter.TO_USER_FILE:
                            case ChatRecyclerAdapter.FROM_USER_VEDIO:
                            case ChatRecyclerAdapter.TO_USER_VEDIO:
                                // showToast("暂未开通群转发");
                                Intent intent = new Intent(ChatGroupActivity.this, SelecteLocalFriendActivity.class);
                                intent.putExtra("tag", 11);
                                intent.putExtra("msg", choseimMessage);
                                startActivityForResult(intent, REQUST_SENDTOFRIEND);
                                break;
                        }
                        break;
                    case R.id.create_group: //收藏
                        String colactiontype = "";
                        if (choseimMessage != null) {
                            Integer messageType = choseimMessage.getMessageType();
                            if (messageType == Constant.MESSAGE_TYPR_TEXT | messageType == Constant.MESSAGE_TYPR_BQEMOJI) {
                                colactiontype = "1";
                            } else if (messageType == Constant.MESSAGE_TYPR_IMAGE) {
                                colactiontype = "2";
                            } else if (messageType == Constant.MESSAGE_TYPR_VOICE) {
                                colactiontype = "3";
                            } else if (messageType == Constant.MESSAGE_TYPR_VEDIO) {
                                colactiontype = "4";
                            }
                            mPgService.addcolaction(colactiontype, choseimMessage.getImageIconUrl(), choseimMessage.getContent(), choseimMessage.getFromname(), ToolsUtils.getMyUserId(), choseimMessage.getFromid() + "").subscribe(new AbsAPICallback<ValidateEntivity>() {
                                @Override
                                protected void onResultError(ApiException ex) {
                                    if (ex != null) {
                                        String displayMessage = ex.getDisplayMessage();
                                        try {
                                            JSONObject object = new JSONObject(displayMessage);
                                            JSONObject data = object.getJSONObject("data");
                                            String info = data.getString("info");
                                            ToolsUtils.showToast(ChatGroupActivity.this, info);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                                @Override
                                public void onNext(ValidateEntivity validateEntivity) {
                                    if (validateEntivity != null) {
                                        ToolsUtils.showToast(ChatGroupActivity.this, validateEntivity.getInfo());
                                    }
                                }
                            });
                        }
                        break;

                    case R.id.search_group: //删除  撤回
                        if (withdraw) {
                            withdrawMsg(sendMsgId);
                        } else {
                            ImMessage msgbyId = ImMessage.findById(ImMessage.class, sendMsgId);
                            msgbyId.delete();//从本地数据库删除
                            for (int o = 0; o < tblist.size(); o++) {
                                ImMessage imMessage = tblist.get(o);
                                if (imMessage.getMsgId().equals(msgbyId.getMsgId())) {
                                    tblist.remove(o);
                                    break;
                                }
                            }
                            tbAdapter.notifyDataSetChanged();
                        }
                        break;

                    case R.id.scan: //更多
                        switch (type) {
                            case ChatRecyclerAdapter.TO_USER_EMOJI:
                            case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
                            case ChatRecyclerAdapter.FROM_USER_EMOJI:
                            case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
                                if (null != choseimMessage) {
                                    String content = "";
                                    try {
                                        MsgEntity msgentity = new Gson().fromJson(choseimMessage.getContent(), MsgEntity.class);
                                        if (null != msgentity) {
                                            content = msgentity.getMsgString();
                                        }
                                        //获取剪贴板管理器：
                                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                        // 创建普通字符型ClipData
                                        ClipData mClipData = ClipData.newPlainText("Label", content);
                                        // 将ClipData内容放到系统剪贴板里。
                                        cm.setPrimaryClip(mClipData);
                                        if (null != content && !"".equals(content))
                                            showToast(getResources().getString(R.string.copy_to_jqb));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                break;
                            default:
                                showToast(getResources().getString(R.string.more_faction_l));
                                break;
                        }
                        // startActivityForResult(CommonScanActivity.class, richScanCode);
                        break;

                    default:
                        break;
                }
                return false;
            }
        });

    }

    /**
     * 撤回消息
     *
     * @param msgid
     */
    @Override
    protected void withdrawMsg(long msgid) {

        setSocket();

        //这里UUID与iOS联通，UUID作为唯一标识，所以本地拼接，规则：聊天类型（单聊是1，群聊是2）+“-”+目标id+“-”+我的id+“-”+时间戳；
        String uuid = "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis();
        WithdrawEntity withdrawEntity = new WithdrawEntity();
        withdrawEntity.setMsgid(sendmsgId);
        String s = new Gson().toJson(withdrawEntity);
        Log.i("info", "s==" + s);
        final ImMessage imMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_WITHDRAW_MSG,
                "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_GROUP,
                destid, s, Constant.MESSAGE_TYPR_WITHDRAW,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, "", fromid + "__" + destid, 0, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());

        imMessage.setFromname(ToolsUtils.getUser().getNickName());
        ImMessage imsgs = ImMessage.findById(ImMessage.class, msgid);
        imsgs.delete();
        for (int e = 0; e < tblist.size(); e++) {
            ImMessage imMessage1 = tblist.get(e);
            //  Log.i("info","imsgs=="+imsgs.getMsgId()+"----"+imMessage1.getMsgId());
            if (imsgs.getMsgId().equals(imMessage1.getMsgId())) {
                tblist.remove(e);
                break;
            }
        }
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);
    }

    private void initBQmm() {
        bqmm = BQMM.getInstance();
//注册UI中的EditView、Keyboard和SendButton
        bqmm.setEditView(mEditTextContent);
        bqmm.setKeyboard(bqmmKeyboard);
        bqmm.setSendButton(sendBtn);
        bqmm.load();

        bqmm.setBqmmSendMsgListener(new IBqmmSendMessageListener() {

            @Override
            public void onSendFace(Emoji face) {
                JSONArray msgCodes = BQMMMessageHelper.getFaceMessageData(face);
                Log.i("info", "msgcodesize==" + msgCodes.length());
                for (int x = 0; x < msgCodes.length(); x++) {
                    try {
                        JSONArray jsonArray = msgCodes.getJSONArray(x);
                        Log.i("info", "array==" + jsonArray);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                MsgEntity msgEntity = new MsgEntity();
                msgEntity.setMsgCodes(msgCodes.toString());
                msgEntity.setMsgString(BQMMMessageHelper.getFaceMessageString(face));
                msgEntity.setMsgType(BQMMMessageText.FACETYPE);
                String msg = new Gson().toJson(msgEntity);
                sendMsg(msg, ChatGroupRecyclerAdapter.TO_USER_EMOJI);
            }

            @Override
            public void onSendMixedMessage(List<Object> emojis, boolean isMixedMessage) {
                String msgString = BQMMMessageHelper.getMixedMessageString(emojis);
                //判断一下文本中是否含有非Unicode表情
                //小表情都是Unicode字符，因此在消息中只含有文字和小表情的时候，这里仍然是false
                MsgEntity msgEntity = new MsgEntity();
                if (isMixedMessage) {//包含其他表情的时候
                    // JSONArray msgCodes = BQMMMessageHelper.getMixedMessageData(emojis);
                    showToast(getResources().getString(R.string.content_emoje_no));
                } else {
                    //文字加小表情或者小表情
                    msgEntity.setMsgString(msgString);
                    msgEntity.setAiteId(friendids);
                    String msg = new Gson().toJson(msgEntity);
                    sendMsg(msg, ChatGroupRecyclerAdapter.TO_USER_EMOJI_TEXT);
                    friendids.clear();
                }
            }
        });
    }

    protected void sendMsg(String msgjson, int typecode) {
        // final String content = mEditTextContent.getText().toString();
        if (msgjson == null || msgjson.equals("")) {
            return;
        }
        setSocket();
        sendMessageHandler.sendEmptyMessage(SEND_CLEAN);
        final ImMessage imMessage = getTbub(0, 1, 0, typecode, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, destid, msgjson, Constant.MESSAGE_TYPR_BQEMOJI,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, null, fromid + "__" + destid, 0, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());
        //  final ImMessage imMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_EMOJI, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, destid, msgjson, Constant.MESSAGE_TYPR_TEXT,
        //          System.currentTimeMillis(), System.currentTimeMillis(), 0, "", fromid + "_" + destid,0,userEntivity.getHeadUrl(),mGroupEntivity.getMarkName());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);

        try {
            MsgEntity msgEntity = new Gson().fromJson(msgjson, MsgEntity.class);
            openklRed(msgEntity.getMsgString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 发送文字
     */
    @Override
    protected void sendMessage() {
        setSocket();

        final String content = mEditTextContent.getText().toString();
        sendMessageHandler.sendEmptyMessage(SEND_CLEAN);
        if (content == null || content.equals("")) {
            return;
        }
        final ImMessage imMessage = getTbub(0, 1, 0, ChatGroupRecyclerAdapter.TO_USER_MSG, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, destid, content, Constant.MESSAGE_TYPR_TEXT,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, null, fromid + "__" + destid, 0, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);

        try {
            openklRed(content);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //发送小视屏
    @Override
    protected void sendVedio(final VedioEntity vedioEntity) {
        setSocket();
        final String vedioPath = vedioEntity.getVedioPath();
        final String vedioBitmappath = vedioEntity.getVedioBitmappath();
        PathEntivity pathEntivity = new PathEntivity(vedioPath, vedioBitmappath);
        String s = new Gson().toJson(pathEntivity, PathEntivity.class);
       /* InputStream is = null;
        try {
            is = new FileInputStream(new File(vedioPath));
            int available = is.available();//文件大小
            float i = (float) available / 1024 / 1024;
            DecimalFormat df = new DecimalFormat("0.00");
            String format = df.format(i);
            vedioEntity.setVedioSize(format+"MB");
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        String content = new Gson().toJson(vedioEntity);
        long currentTime = System.currentTimeMillis();
        final ImMessage  vedioMessage = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_VEDIO, "2-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_GROUP, destid, content, Constant.MESSAGE_TYPR_VEDIO,
                currentTime, System.currentTimeMillis(), 0, s, fromid + "__" + destid, 0, userEntivity.getHeadUrl(), mGroupEntivity.getMarkName());
        tblist.add(vedioMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String vedioimgurl = HttpAssist.uploadFile(new File(vedioBitmappath), vedioMessage.getMsgId(), false);//上传缩略图
                String destPath =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
                String vediourl;
                if(ToolsUtils.getFileSize(new File(vedioPath))<ToolsUtils.MIN_STORAGE){
                    Log.d("huangrui","没有压缩:");
                    vediourl = HttpAssist.uploadFile(new File(vedioPath), vedioMessage.getMsgId(), false);//上传视屏
                }else{
                    String filePath="";
                    Log.d("huangrui","输入路径:"+vedioPath);
                    try {
                        Log.d("huangrui","输出路径:"+destPath);
                        filePath = SiliCompressor.with(ChatGroupActivity.this).compressVideo(vedioPath, destPath);
                        Log.d("huangrui","生成路径:"+filePath);
                    }catch (Exception e){

                    }
                    vediourl = HttpAssist.uploadFile(new File(filePath), vedioMessage.getMsgId(), false);//上传视屏
                    Log.d("huangrui","上传路径:"+vediourl);
                }

                ImageEntity img1 = new Gson().fromJson(vedioimgurl, ImageEntity.class);
                ImageEntity img2 = new Gson().fromJson(vediourl, ImageEntity.class);
                vedioEntity.setVedioUrl(img2.getData().getInfo().get(0));
                vedioEntity.setGetVedioBitmapUrl(img1.getData().getInfo().get(0));
                String vediocontent = new Gson().toJson(vedioEntity);
                vedioMessage.setContent(vediocontent);
                //sendMessageHandler.sendEmptyMessage(VEDIO_FINISH);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        socketSend(vedioMessage, null, 0, 0);
                    }
                });
            }
        }).start();
    }

    //接收录制的小视屏
    @Subscribe(threadMode = ThreadMode.MAIN) //
    public void onsendvedio(VedioEntity vedio) {
        if (vedio != null) {
            sendVedio(vedio);
        } else {
            showToast("小视屏获取失败");
        }

    }

    //重写此方法解决AudioManager 导致的内存泄漏
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name))
                    return getApplicationContext().getSystemService(name);
                return super.getSystemService(name);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (tbbv.getVisibility() == View.VISIBLE) {
                tbbv.setVisibility(View.GONE);
                mess_iv.setImageResource(R.drawable.tb_more);
                return true;
            }
        }
        super.onKeyDown(keyCode, event);
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEventMainThread(EventBusTypeObject event) {
        if (null != event && event.getType() == EventBusType.SHOW_MAIN_TOAST) {
            if (event.getUid().equals("" + destid)) {
                finish();
            }
        }

    }


    private void toReadPackHistoryActivity(long delayMillions, final boolean canOpen) {

        PGService.getInstance().getRedPacketHistory(redPacketInfo, ToolsUtils.getMyUserId())
                .delay(delayMillions, TimeUnit.MILLISECONDS)
                .compose(RxJavaUtil.<RedPacketHistoryEntivity>applySchedules())
                .compose(ChatGroupActivity.this.<RedPacketHistoryEntivity>bindLifeCycle())
                .subscribe(new AbsAPICallback<RedPacketHistoryEntivity>() {
                    @Override
                    protected void onResultError(ApiException ex) {
                        new ToastUtils().showSingleToast(ex.getDisplayMessage());
                        hideProgress();
                    }

                    @Override
                    public void onNext(RedPacketHistoryEntivity data) {
                        doCancelRain();
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("redPacketId", data);
                        bundle.putInt("type", 1);
                        if (!canOpen) {
                            bundle.putString("status", "1");
                        }
                        startActivity(RedPackageDetailsActivity.class, bundle);
                    }
                });
    }

    /**
     * 是否被禁言
     *
     * @return
     */
    private boolean isAnExcuse() {

        return ToolsUtils.getLastAnExcuseTime(String.valueOf(destid), fromid) > 0
                || ToolsUtils.isAnExcuseAllGroupMember(destid);
    }

    /*
    重新写的弹框提示群主群成员快到期
     */
/*
    @Override
    protected void onPostResume() {
        super.onPostResume();
        msgDialog.setDialogSize(300,300);
        msgDialog.show();
    }*/
}